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.

2
  • 1
    preg_replace accepts a regular expression as first parameter. Commented Mar 17, 2014 at 5:31
  • possible duplicate of Replace string only once with php preg_replace Commented Mar 17, 2014 at 5:46

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.