PHP iterate String look for a certain pattern and replace

ucsdmbdm used Ask the Experts™
I was wondering whats the best way of walking through a string and replacing a word followed by unknown number of letters within the string (I guess some sort of regular expression) but not sure whats the best way of doing so. Here is a sample:

$sample_String => "I am sitting with member_21 and member_1234 and member_";

I would like to go through the string above and get every  member_??? (unknown number), call a function on it and replace them with whatever the function returns. For simplicity lets say I want this function to return the number of digits in front of each member_??? and replaces them.

The above string should become:
$final_String = "I am sitting with 2 and 4 and 0"
(since first number has 2 digits, second has 4 and third has 0 digits)

I am sure there are many ways but I'd like to find the most efficient way

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®


I used the following & it worked.  

$converted_string = "";
            $array = explode(" ",$sample_String);
            foreach($array as $key => $value) {
                   if (strstr($value, 'member_')){
                        $value = substr($value,7);
                        // call function on value to get number of digits
                  $final_String = $converted_string." ".$value;

Please only respond if your way is shorter :)
$sample_String = "I am sitting with member_21 and member_1234 and member_";
preg_match_all('/member_(\d*)/', $sample_String, $matches);

foreach($matches[0] as $m)
      $c = process_match($m);
      $sample_String=preg_replace("/$m/", $c, $sample_String);


echo $sample_String;

function process_match($v)
      preg_match('/member_(\d*)/', $v, $matches2);
      return (strlen($matches2[1]));

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial