str_ireplace will not work with single quote
I want to replace single quote (') in a string.
Apparently this w开发者_运维百科ill not work...:
$patterns = array();
$replacements = array();
$patterns[0] = "'";
$patterns[1] = '\'';
$replacements[0] = 'Something';
$replacements[2] = 'Same thing just in a other way';
Replacing ('
) with ("
) works fine for me with str_ireplace
.
$test = str_ireplace("'", "\"", "I said 'Would you answer me?'");
echo $test; // I said "Would you answer me?"
Also works fine replacing ("
) with ('
)
$test = str_ireplace("\"", "'", "I said \"Would you answer me?\"");
echo $test; // I said 'Would you answer me?'
It looks like your sample code has been over anonymised (indexes 0 & 2 for $replacements?) and over truncated (where is the str_ireplace call) however... I'll take a guess that you haven't fully understood str_ireplace.
The first point is that str_ireplace does not work in place. It's return value is the altered string/array of strings.
The second point is that, when you have an array of searches and replacements, PHP will work through taking one item from each array and applying it to the subject/array of subjects, before moving on to the next item from each array and then applying that to the same subject(s). You can see this in the example below where both subjects have had "'" replaced with "something" and "Same thing just in a other way" never makes an appearance in the results.
$patterns = array();
$replacements = array();
$patterns[0] = "'";
$patterns[1] = '\'';
$replacements[0] = 'Something';
$replacements[1] = 'Same thing just in a other way';
$subjects[0] = "I've included a single quote.";
$subjects[1] = "This'll also have a quote.";
$newSubjects = str_ireplace($patterns, $replacements, $subjects);
print_r($newSubjects);
When run this gives
Array ( [0] => ISomethingve included a single quote. [1] => ThisSomethingll also have a quote. )
精彩评论