eg. I want to replace instances of some words with their string length
开发者_运维技巧"XXXX is greater than XX" becomes "4 is greater than 2"
Code that I intend to write :
$myStrings = Array("XX","XXX","XXXX","XXXXX");
$outStr = str_replace($myStrings,strlen(current($myStrings)),$outStr);
But here CURRENT is not working.
P.S. Please do not suggest workarounds to do this stuff since that is not what I intend to ask the forum. My query is getting current pointer to an array being traversed internally.
Thank You.
The function you are looking for is array_map
. It applies a function to all elements of an array and outputs the results as a new array:
$myStrings = Array("XX","XXX","XXXX","XXXXX");
$outStr = str_replace($myStrings,array_map('strlen', $myStrings)),$outStr);
This might create a new problem as XXXX will be replaced with 22 before XXXX is checked. The solution to this would be reverse the input array:
$myStrings = array_reverse(Array("XX","XXX","XXXX","XXXXX"));
$outStr = str_replace($myStrings,array_map('strlen', $myStrings)),$outStr);
I don't think you can. Since it's an internal implementation, what would PHP expose to you that you could use to determine the current element?
Note that this is different from accessing internal array pointers using current()
, key()
, next()
, reset()
et al. I'm referring to the fact that PHP has an internal implementation of str_replace()
for handling replacements of arrays of strings.
A quick test reveals that PHP doesn't even seem to bother with array pointers when replacing them with str_replace()
anyway:
$arr = array('a', 'b', 'c'); // Internal pointer is at a
$str = 'abc';
next($arr); // Internal pointer is at b
echo str_replace($arr, 'x', $str), "\n"; // xxx
echo current($arr), "\n"; // b
Oh, by the way, this is what the manual for str_replace()
says (strong emphasis mine):
If
search
is an array andreplace
is a string, then this replacement string is used for every value ofsearch
.
So specifically for str_replace()
, I don't think it was ever intended for you to pass in a replacement string that is dynamic based on the input array.
And http://www.php.net/manual/de/function.array-walk.php isn´t an option?
精彩评论