[英]str_replace alternative for PHP
In the str_replace
manual for PHP it states the following: 在PHP的str_replace
手册中 ,它说明了以下内容:
Because
str_replace()
replaces left to right, it might replace a previously inserted value when doing multiple replacements. 因为str_replace()
从左向右替换,所以在执行多次替换时,它可能会替换先前插入的值。 See also the examples in this document. 另请参阅本文档中的示例。
Is there an equivalent function that does not have this gotcha or how can I safely do this? 是否有一个没有这个问题的等效功能或我怎样才能安全地做到这一点?
You're looking for strtr ( string $str , array $replace_pairs )
. 你正在寻找strtr ( string $str , array $replace_pairs )
。
If given two arguments, the second should be an array in the form array('from' => 'to', ...). 如果给出两个参数,则第二个应该是表单数组中的数组('from'=>'到',...)。 The return value is a string where all the occurrences of the array keys have been replaced by the corresponding values. 返回值是一个字符串,其中所有出现的数组键都已被相应的值替换。 The longest keys will be tried first . 最长的键将被首先尝试。 Once a substring has been replaced, its new value will not be searched again. 替换子字符串后, 将不再搜索其新值。
Example from the manual: 手册中的示例:
<?php
$trans = array("h" => "-", "hello" => "hi", "hi" => "hello");
echo strtr("hi all, I said hello", $trans);
?>
Will output: 将输出:
hello all, I said hi 大家好,我说嗨
Which should be exactly what you need. 这应该是你需要的。
Use preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )
im pretty sure you could make it replace all the values or one if thats what you're asking. 使用preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )
我很确定你可以让它替换所有的值或者如果那就是你的内容问。
Or you could do it in pieces if theres an order to replace what you want 或者你可以分成几块,如果有一个订单来取代你想要的
$value = preg_replace($pattern1, '..', $value);
$value = preg_replace($pattern2, '..', $value);
$value = preg_replace($pattern3, '..', $value);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.