php str_replace 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13715826/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
str_replace with array
提问by LautaroAngelico
I'm having some troubles with the PHP function str_replacewhen using arrays.
str_replace使用数组时,我在使用PHP 函数时遇到了一些麻烦。
I have this message:
我有这个消息:
$message = strtolower("L rzzo rwldd ty esp mtdsza'd szdepw ty esp opgtw'd dple");
And I am trying to use str_replacelike this:
我正在尝试这样使用str_replace:
$new_message = str_replace(
array('l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','a','b','c','d','e','f','g','h','i','j','k'),
array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'),
$message);
The result should be A good glass in the bishop's hostel in the devil's seat, but instead, I get p voos vlpss xn twt qxswop's wosttl xn twt stvxl's stpt.
结果应该是A good glass in the bishop's hostel in the devil's seat,但相反,我得到了p voos vlpss xn twt qxswop's wosttl xn twt stvxl's stpt。
However, when I only try replacing 2 letters it replaces them well:
但是,当我只尝试替换 2 个字母时,它会很好地替换它们:
$new_message = str_replace(array('l','p'), array('a','e'), $message);
the letters land pwill be replaced by aand e.
字母l和p将替换为a和e。
Why is it not working with the full alphabet array if they are both exactly the same size?
如果它们的大小完全相同,为什么不能使用完整的字母数组?
采纳答案by Ry-
str_replacewith arrays just performs all the replacements sequentially. Use strtrinstead to do them all at once:
str_replacewith 数组只是按顺序执行所有替换。使用strtr代替一次性完成所有操作:
$new_message = strtr($message, 'lmnopq...', 'abcdef...');
回答by Rakesh Tembhurne
Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements.
因为 str_replace() 从左到右替换,所以在进行多次替换时它可能会替换之前插入的值。
// Outputs F because A is replaced with B, then B is replaced with C, and so on...
// Finally E is replaced with F, because of left to right replacements.
$search = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'A';
echo str_replace($search, $replace, $subject);
回答by desiweb.ir
回答by TwystO
Alternatively to the answer marked as correct, if you have to replace words instead of chars you can do it with this piece of code :
除了标记为正确的答案之外,如果您必须替换单词而不是字符,您可以使用这段代码来完成:
$query = "INSERT INTO my_table VALUES (?, ?, ?, ?);";
$values = Array("apple", "oranges", "mangos", "papayas");
foreach (array_fill(0, count($values), '?') as $key => $wildcard) {
$query = substr_replace($query, '"'.$values[$key].'"', strpos($query, $wildcard), strlen($wildcard));
}
echo $query;
Demo here : http://sandbox.onlinephpfunctions.com/code/56de88aef7eece3d199d57a863974b84a7224fd7
演示在这里:http: //sandbox.onlinephpfunctions.com/code/56de88aef7eece3d199d57a863974b84a7224fd7
回答by David H.
If the text is a simple markup and has existing anchors, stage the existing anchor tags first, swap out the urls, then replace the staged markers.
如果文本是一个简单的标记并具有现有锚点,请先暂存现有的锚点标签,换出 url,然后替换暂存的标记。
$text = '
Lorem Ipsum is simply dummy text found by searching http://google.com/?q=lorem in your <a href=https://www.mozilla.org/en-US/firefox/>Firefox</a>,
<a href="https://www.apple.com/safari/">Safari</a>, or https://www.google.com/chrome/ browser.
Link replacements will first stage existing anchor tags, replace each with a marker, then swap out the remaining links.
Links should be properly encoded. If links are not separated from surrounding content like a trailing "." period then they it will be included in the link.
Links that are not encoded properly may create a problem, so best to use this when you know the text you are processing is not mixed HTML.
Example: http://google.com/i,m,complicate--d/index.html
Example: https://www.google.com/chrome/?123&t=123
Example: http://google.com/?q='. urlencode('<a href="http://google.com">http://google.com</a>') .'
';
// Replace existing links with a marker
$linkStore = array();
$text = preg_replace_callback('/(<a.*?a>)/', function($match) use (&$linkStore){ $key = '__linkStore'.count($linkStore).'__'; $linkStore[$key] = $match[0]; return $key; }, $text);
// Replace remaining URLs with an anchor tag
$text = preg_replace_callback("/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/", function($match) use (&$linkStore){ return '<a href="'. $match[0] .'">'. $match[0] .'</a>'; }, $text);
// Replace link markers with original
$text = str_replace(array_keys($linkStore), array_values($linkStore), $text);
echo '<pre>'.$text;

