Search code examples
phphtmlpreg-replacepreg-match-allsrc

php - change value to src attribute if 'cid:' are found in html document


how can I tell php to look if a src attribute starts with 'cid:' and if yes, replace it with another value?

<img src="cid:xx_xxxxxxxx_xxxxxxxxxxxxxxxxxxx" width="544" height="340">

<?php
    $new_link = "http://www.example.com'";
    preg_replace("#^cid:#", $new_link);
?>

Solution

  • The ^ is for the start of a string or line depending on the modifier being used. You want

    <?php
    $new_link = "http://www.example.com'";
    echo preg_replace('~src="cid.*?"~',"src='$new_link'", '<img src="cid:xx_xxxxxxxx_xxxxxxxxxxxxxxxxxxx" width="544" height="340">');
    ?>
    

    Output:

    <img src='http://www.example.com'' width="544" height="340">
    

    The second trailing single quote at the end of the src is from the $newlink.

    The . is for any character * for any number of "any characters" and the ? says stop at the first occurrence of the next character. In this case that is a double quote which should make this capture the whole string src attribute.

    If the src can be using both single or double quotes this should account for that (also note i removed the trailing quote here from $newlink).

    <?php
    $new_link = "http://www.example.com";
    echo preg_replace('~src=("|\')cid.*?\1~',"src='$new_link'", '<img src="cid:xx_xxxxxxxx_xxxxxxxxxxxxxxxxxxx" width="544" height="340">');
    ?>