0

I am testing the str_replace in phpList and I want to replace the first match of a string. I found on other posts that I should use preg_replace if I want to replace the first match of a string, the problem is preg_replace does not return a string for some reason.

Both

$fp = fopen('/var/www/data.txt', 'w');
$string_test = preg_replace(basename($html_images[$i]), "cid:$cid", $this->Body,1);
fwrite($fp,$string_test);
fclose($fp);

and

$fp = fopen('/var/www/data.txt', 'w');
fwrite($fp,preg_replace(basename($html_images[$i]), "cid:$cid", $this->Body,1));
fclose($fp);

writes an empty string to the file. I would like to know how to get a return string and str_replace does not seem to work with first match. However, str_replace would return a string.

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
user1352777
  • 81
  • 1
  • 1
  • 10
  • 1
    preg_replace accepts a regular expression as first parameter. – xdazz Mar 17 '14 at 05:31
  • possible duplicate of [Replace string only once with php preg\_replace](http://stackoverflow.com/questions/3392508/replace-string-only-once-with-php-preg-replace) – Ja͢ck Mar 17 '14 at 05:46

2 Answers2

0

preg_replace()'s does a Regular Expression match and replace. You are passing it a string instead of a valid RegEx as the first argument.

Instead you might be looking for str_replace() which does string replacement.

Itay Grudev
  • 7,055
  • 4
  • 54
  • 86
  • I will look into Regular Expression. I tried this fwrite($fp,str_replace(basename($html_images[$i]), "cid:$cid", $this->Body,1)); with str_replace, it does not seem to work. – user1352777 Mar 17 '14 at 05:39
0

Actually, preg_replace() is the wrong tool if you just want to perform a regular find & replace operation. You could perform a single replacement using strpos() and substr_replace() for instance:

$find = basename($html_images[$i]);
$string_test = $this->Body;
if (($pos = strpos($string_test, $find)) !== false) {
    $string_test = substr_replace($string_test, "cid:$cid", $pos, strlen($find));
}

With preg_replace() you would get something like this:

$string_test = preg_replace('~' . preg_quote(basename($html_images[$i], '~') . '~', "cid:$cid", $this->Body, 1);

For convenience, you can wrap either two into a function called str_replace_first().

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309