Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace the same characters with different strings

Assuming I have a string

$str = "abc*efg*hij*";

and an array

$arr = array("123","456","789");

Now I want to replace the *s in $str with the elements in $arr according to the positions.The first * replaced with $arr[0],the second replaced with $arr[1] etc.I check the function str_replace,though it accepts arrays as parameters but I found it did not work.And I cannot just use

$newstr = "abc{$arr[0]}efg{$arr[1]}hij{$arr[2]}"

because the real $str may be quite a long string with lots of *.Any good ideas?Thanks.

like image 511
Young Avatar asked Oct 21 '10 05:10

Young


People also ask

How do I replace a string in a different string?

To replace one string with another string using Java Regular Expressions, we need to use the replaceAll() method. The replaceAll() method returns a String replacing all the character sequence matching the regular expression and String after replacement.

Can you replace multiple strings in Python?

Replace multiple different substringsThere is no method to replace multiple different strings with different ones, but you can apply replace() repeatedly.

How do you replace multiple characters in a string in Python?

A character in Python is also a string. So, we can use the replace() method to replace multiple characters in a string. It replaced all the occurrences of, Character 's' with 'X'.


1 Answers

If * is your only format character, try converting * to %s (also escape existing % to %%), and then using vsprintf(), which takes an array of values to pass in as format parameters:

$str = str_replace(array('%', '*'), array('%%', '%s'), $str);
$newstr = vsprintf($str, $arr);
echo $newstr;

Output:

abc123efg456hij789

Note that if you have more array elements than asterisks, the extra elements at the end simply won't appear in the string. If you have more asterisks than array elements, vsprintf() will emit a too-few-arguments warning and return false.

like image 143
BoltClock Avatar answered Sep 21 '22 04:09

BoltClock