Link to home
Start Free TrialLog in
Avatar of ucsdmbdm
ucsdmbdm

asked on

PHP iterate String look for a certain pattern and replace

Hi,
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

Thanks,
Avatar of ucsdmbdm
ucsdmbdm

ASKER

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 :)
ASKER CERTIFIED SOLUTION
Avatar of Justin Mathews
Justin Mathews

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial