1

I want to do a str_replace for a HTML String, everytime find a match item the value will increase as well.

$link = 1;

$html = str_replace($this->link, $link, $html);

This would replace all in once, and with same string $link, i would like the $link increase every time it found an match. is it possible?

Thanks very much

2

2 Answers 2

2

You can use a regular expression to return how many replacements it does.

<?php
$string = "red green green blue red";

preg_replace('/\b(green)\b/i', '[removed]', $string, -1 , $results);
echo $results; // returns '2' as it replaces green twice with [removed]
?>
Sign up to request clarification or add additional context in comments.

Comments

1

If I understand you correctly (you want each match replaced with growing integer), it would seem the comments on the question encouraging you to use preg_replace_callback would be correct:

$str = 'Hello World';
$cnt = 0;

function myCallback ( $matches ) {
  global $cnt;
  return ++$cnt;
}

// He12o Wor3d
echo preg_replace_callback( '/\l/', 'myCallback', $str );

3 Comments

this myCallback, what if its in a Class? echo preg_replace_callback( '/\l/', $this->myCallback, $str ); doesn't work
preg_replace_callback( '/\l/', array($this, 'myCallback'), $text);
preg_replace_callback( '/\l/', 'self::myCallback', $text); this works as well

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.