php 如何替换我的字符串的某些部分?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8163746/
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
How do I replace certain parts of my string?
提问by Stian
How can I replace a certain part of my string with another one?
如何用另一部分替换我的字符串的某个部分?
Input string:
输入字符串:
"Hello, my name is Santa"
How can I change all a's in my string with something else?
我怎样才能a用别的东西改变我的字符串中的all ?
I think I need a foreachloop, but I'm unsure how to use it.
我想我需要一个foreach循环,但我不确定如何使用它。
回答by zrvan
strtr ($str, array ('a' => '<replacement>'));
Or to answer your question more precisely:
或者更准确地回答您的问题:
strtr ("Hello, my name is Santa", array ('a' => '<replacement>'));
回答by Rizier123
Search & Replace
搜索和替换
There are a few different functions/methods to replace a certain part of a string with something else, all with their own advantages.
有几种不同的函数/方法可以用其他东西替换字符串的某个部分,所有这些都有自己的优点。
str_replace()method (binary safe; case-sensitive)
str_replace()方法(二进制安全;区分大小写)
Arguments
参数
mixed str_replace ( mixed $search, mixed $replace, mixed $subject[, int &$count ] )
混合 str_replace (混合$search,混合$replace,混合$subject[, int &$count ] )
str_replace()has 3 required arguments as you can see in the above definition with the correct order, all of which can take a string as also an array as argument!
str_replace()有 3 个必需参数,如您在上面的定义中看到的,顺序正确,所有这些参数都可以将字符串作为数组作为参数!
Search & Replace
搜索和替换
search(string) AND replace(string)→ Replaces the search string with the replace string.
search(array) AND replace(string)→ Replaces all search elements with the replace string.
search(string) AND replace(array)→ Throws you a notice: "Notice: Array to string conversion", because a replacement array for just one search string doesn't make sense, so it triesto convert the array to a string.
search(array) AND replace(array)→ Replaces each search element with the corresponding replace element (Keys are ignored!).
search(more elements) AND replace(less elements)→ Replaces each search element with the corresponding replace element (For the missing replace elements an empty string will be used).
search(less elements) AND replace(more elements)→ Replaces each search element with the corresponding replace element (Unneeded replace elements are ignored).
search(string) AND replace(string)→ 用替换字符串替换搜索字符串。
search(array) AND replace(string)→ 用替换字符串替换所有搜索元素。
search(string) AND replace(array)→ 向您抛出一条通知:“注意:数组到字符串的转换”,因为仅替换一个搜索字符串的数组没有意义,因此它会尝试将数组转换为字符串。
search(array) AND replace(array)→ 用相应的替换元素替换每个搜索元素(忽略键!)。
search(more elements) AND replace(less elements)→ 用相应的替换元素替换每个搜索元素(对于缺少的替换元素,将使用空字符串)。
search(less elements) AND replace(more elements)→ 用相应的替换元素替换每个搜索元素(忽略不需要的替换元素)。
Subject
主题
subject(string)→ Replacement is done for the subject string.
subject(array)→ Replacement is done for each array element.
subject(string)→ 已完成主题字符串的替换。
subject(array)→ 对每个数组元素进行替换。
Code
代码
echo str_replace("search", "replace", "text search text");
echo str_replace(["t", "a"], "X", "text search text");
echo str_replace("search", ["replace1", "replace2"], "text search text");
echo str_replace(["a", "c"], ["X", "Y"], "text search text");
Output
输出
text replace text
XexX seXrch XexX
Notice: Array to string conversion
text seXrYh text
Notes
笔记
Gotcha!
Important to know is that
str_replace()works from left to right of the array. This means it can possible replace a value which you already replaced. For example:echo str_replace(array("a", "b"), array("b", "c"), "aabb"); //Probably expected output: bbcc //Actual output: ccccCase insensitive
If you want to make the search case insensitive you can use
str_ireplace()(Notice theifor case-insensitive).Multidimensional array
str_replace()/str_ireplace()does NOT work for multidimensional arrays. See this manual commentfor such an implementation. Of course you can also replacestr_replace()withstr_ireplace()for case-insensitive.
知道了!
重要的是要知道它
str_replace()从数组的左到右工作。这意味着它可以替换您已经替换的值。例如:echo str_replace(array("a", "b"), array("b", "c"), "aabb"); //Probably expected output: bbcc //Actual output: cccc不区分大小写
如果你想搜索不区分大小写,您可以使用
str_ireplace()(注意,i为区分我nsensitive)。多维数组
str_replace()/str_ireplace()不适用于多维数组。有关此类实现,请参阅此手册注释。当然你也可以更换str_replace()与str_ireplace()不区分大小写。
If you want to put everything together and create a function that also works for multidimensional arrays case-insensitive you can do something like this:
如果您想将所有内容放在一起并创建一个也适用于不区分大小写的多维数组的函数,您可以执行以下操作:
<?php
function str_ireplace_deep($search, $replace, $subject)
{
if (is_array($subject))
{
foreach($subject as &$oneSubject)
$oneSubject = str_ireplace_deep($search, $replace, $oneSubject);
unset($oneSubject);
return $subject;
} else {
return str_ireplace($search, $replace, $subject);
}
}
?>
strtr()method (50% binary safe; case-sensitive)
strtr()方法(50% 二进制安全;区分大小写)
Arguments
参数
string strtr ( string $str, string $from, string $to)
string strtr ( string $str, array $replace_pairs)
字符串 strtr ( 字符串$str, 字符串$from, 字符串$to)
字符串 strtr ( 字符串$str,数组$replace_pairs)
The function either takes 3 arguments with a from and to string or it takes 2 arguments with a replacement array array("search" => "replace" /* , ... */), all of which you can see in the above definition with the correct order.
该函数要么接受 3 个带有 from 和 to 字符串的参数,要么接受 2 个带有替换数组的参数array("search" => "replace" /* , ... */),所有这些都可以在上面的定义中以正确的顺序看到。
2 Arguments
2 参数
It starts to replace the longest key with the corresponding value and does this until it replaced all key => valuepairs. In this case the function is binary safe, since it uses the entire key/value.
它开始用相应的值替换最长的键并执行此操作,直到替换所有key => value对。在这种情况下,该函数是二进制安全的,因为它使用整个键/值。
3 Arguments
3 个参数
It replaces the from argument with the to argument in the subject byte by byte. So it is not binary safe!
它将主题中的 from 参数逐个字节替换为 to 参数。所以它不是二进制安全的!
If the from and to arguments are of unequal length the replacement will stop when it reaches the end of the shorter string.
如果 from 和 to 参数的长度不相等,则替换将在到达较短字符串的末尾时停止。
Subject
主题
It doesn't accept an array as subject, just a string.
它不接受一个数组作为主题,只是一个字符串。
Code
代码
echo strtr("text search text", "ax", "XY");;
echo strtr("text search text", ["search" => "replace"]);
Output
输出
teYt seXrch teYt
text replace text
Notes
笔记
Gotcha!
Opposed to
str_replace(),strtr()does NOT replace something twice. As an example:echo strtr("aabb", ["a" => "b", "b" => "c"]); //Expected output: bbcc //Actual output: bbccAlso if you want to replace multiple things with the same string you can use
array_fill_keys()to fill up your replacement array with the value.Case insensitive
strtr()is NOT case-insensitive NOR is there a case-insensitive equivalent function. See this manual commentfor a case-insensitive implementation.Multidimensional array
strtr()does opposed tostr_replace()NOT work with arrays as subject, so it also does NOT work with multidimensional arrays. You can of course use the code above fromstr_replace()for multidimensional arrays and just use it withstrtr()or the implementation ofstritr().
知道了!
反对
str_replace(),strtr()不会两次替换某些东西。举个例子:echo strtr("aabb", ["a" => "b", "b" => "c"]); //Expected output: bbcc //Actual output: bbcc此外,如果您想用相同的字符串替换多个内容,您可以使用
array_fill_keys()该值填充替换数组。不区分大小写
strtr()不是不区分大小写 NOR 是否有不区分大小写的等效函数。有关不区分大小写的实现,请参阅此手册注释。多维数组
strtr()不反对将str_replace()数组作为主题,因此它也不适用于多维数组。您当然可以将上面的代码str_replace()用于多维数组,并将其与strtr()或 的实现一起使用stritr()。
If you want to put everything together and create a function that also works for multidimensional arrays case-insensitive you can do something like this:
如果您想将所有内容放在一起并创建一个也适用于不区分大小写的多维数组的函数,您可以执行以下操作:
<?php
if(!function_exists("stritr")){
function stritr($string, $one = NULL, $two = NULL){
/*
stritr - case insensitive version of strtr
Author: Alexander Peev
Posted in PHP.NET
*/
if( is_string( $one ) ){
$two = strval( $two );
$one = substr( $one, 0, min( strlen($one), strlen($two) ) );
$two = substr( $two, 0, min( strlen($one), strlen($two) ) );
$product = strtr( $string, ( strtoupper($one) . strtolower($one) ), ( $two . $two ) );
return $product;
}
else if( is_array( $one ) ){
$pos1 = 0;
$product = $string;
while( count( $one ) > 0 ){
$positions = array();
foreach( $one as $from => $to ){
if( ( $pos2 = stripos( $product, $from, $pos1 ) ) === FALSE ){
unset( $one[ $from ] );
}
else{
$positions[ $from ] = $pos2;
}
}
if( count( $one ) <= 0 )break;
$winner = min( $positions );
$key = array_search( $winner, $positions );
$product = ( substr( $product, 0, $winner ) . $one[$key] . substr( $product, ( $winner + strlen($key) ) ) );
$pos1 = ( $winner + strlen( $one[$key] ) );
}
return $product;
}
else{
return $string;
}
}/* endfunction stritr */
}/* endfunction exists stritr */
function stritr_deep($string, $one = NULL, $two = NULL){
if (is_array($string))
{
foreach($string as &$oneSubject)
$oneSubject = stritr($string, $one, $two);
unset($oneSubject);
return $string;
} else {
return stritr($string, $one, $two);
}
}
?>
preg_replace()method (binary safe; case-sensitive)
preg_replace()方法(二进制安全;区分大小写)
Arguments
参数
mixed preg_replace ( mixed $pattern, mixed $replacement, mixed $subject[, int $limit = -1 [, int &$count ]] )
混合 preg_replace (混合$pattern,混合$replacement,混合$subject[, int $limit = -1 [, int &$count ]] )
preg_replace()has 3 required parameters in the order shown above. Now all 3 of them can take a string as also an array as argument!
preg_replace()按上面显示的顺序有 3 个必需的参数。现在他们三个都可以将字符串作为数组作为参数!
Search & Replace
搜索和替换
search(string) AND replace(string)→ Replaces all matches of the search regex with the replace string.
search(array) AND replace(string)→ Replaces all matches of each search regex with the replace string.
search(string) AND replace(array)→ Throws you a warning: "Warning: preg_replace(): Parameter mismatch, pattern is a string while replacement is an array", because a replacement array for just one search regex doesn't make sense.
search(array) AND replace(array)→ Replaces all matches of each search regex with the corresponding replace element(Keys are ignored!).
search(more elements) AND replace(less elements)→ Replaces all matches of each search regex with the corresponding replace element(For the missing replace elements an empty string will be used).
search(less elements) AND replace(more elements)→ Replaces all matches of each search regex with the corresponding replace element(Unneeded replace elements are ignored).
search(string) AND replace(string)→ 用替换字符串替换搜索正则表达式的所有匹配项。
search(array) AND replace(string)→ 用替换字符串替换每个搜索正则表达式的所有匹配项。
search(string) AND replace(array)→ 向您抛出警告:“警告:preg_replace():参数不匹配,模式是字符串而替换是数组”,因为仅用于一个搜索正则表达式的替换数组没有意义。
search(array) AND replace(array)→ 用相应的替换元素替换每个搜索正则表达式的所有匹配项(键被忽略!)。
search(more elements) AND replace(less elements)→ 用相应的替换元素替换每个搜索正则表达式的所有匹配项(对于缺少的替换元素,将使用空字符串)。
search(less elements) AND replace(more elements)→ 用相应的替换元素替换每个搜索正则表达式的所有匹配项(忽略不需要的替换元素)。
Subject
主题
subject(string)→ Replacement is done for the subject string.
subject(array)→ Replacement is done for each array element.
subject(string)→ 已完成主题字符串的替换。
subject(array)→ 对每个数组元素进行替换。
Please note again: The search must be a regular expression! This means it needs delimiters and special characters need to be escaped.
再次请注意:搜索必须是正则表达式!这意味着它需要分隔符并且需要转义特殊字符。
Code
代码
echo preg_replace("/search/", "replace", "text search text");
echo preg_replace(["/t/", "/a/"], "X", "text search text");
echo preg_replace("/search/", ["replace1", "replace2"], "text search text");
echo preg_replace(["a", "c"], ["X", "Y"], "text search text");
Output
输出
text replace text
XexX seXrch XexX
Warning: preg_replace(): Parameter mismatch, pattern is a string while replacement is an array
text seXrYh text
Notes
笔记
Gotcha!
Same as
str_replace(),preg_replace()works from left to right of the array. This means it can possible replace a value which you already replaced. For example:echo preg_replace(["/a/", "/b/"], ["b", "c"], "aabb"); //Probably expected output: bbcc //Actual output: ccccCase insensitive
Since the search argument is a regular expression you can simply pass the
flag ifor case-insensitive search.Multidimensional array
preg_replace()does NOT work for multidimensional arrays.Backreference
Be aware that you can use
\\n/$nas backreference to your capturing groups of the regex. Where0is the entire match and1-99for your capturing groups.Also if the backreference is immediately followed by a number you have to use
\${n}.Replacement / "The /e modifier is deprecated"
The replacement in
preg_replace()can't use callback functions as replacements. So you have to usepreg_replace_callback(). Same when you use the modifiereand get "Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead". See: Replace preg_replace() e modifier with preg_replace_callback
知道了!
与 相同
str_replace(),preg_replace()从数组的左到右工作。这意味着它可以替换您已经替换的值。例如:echo preg_replace(["/a/", "/b/"], ["b", "c"], "aabb"); //Probably expected output: bbcc //Actual output: cccc不区分大小写
由于搜索参数是一个正则表达式,您可以简单地传递
flag i不区分大小写的搜索。多维数组
preg_replace()不适用于多维数组。反向引用
请注意,您可以使用
\\n/$n作为对正则表达式捕获组的反向引用。0整个比赛和1-99您的捕获组在哪里。此外,如果反向引用后紧跟一个数字,则必须使用
\${n}.替换/“不推荐使用 /e 修饰符”
中的替换
preg_replace()不能使用回调函数作为替换。所以你必须使用preg_replace_callback(). 当您使用修饰符e并获得“已弃用:preg_replace():不推荐使用 /e 修饰符,请改用 preg_replace_callback”时相同。请参阅:用 preg_replace_callback 替换 preg_replace() e 修饰符
If you want to put everything together and create a function that also works for multidimensional arrays case-insensitive you can do something like this:
如果您想将所有内容放在一起并创建一个也适用于不区分大小写的多维数组的函数,您可以执行以下操作:
<?php
function preg_replace_deep($search, $replace, $subject)
{
if (is_array($subject))
{
foreach($subject as &$oneSubject)
$oneSubject = preg_replace_deep($search, $replace, $oneSubject);
unset($oneSubject);
return $subject;
} else {
return preg_replace($search, $replace, $subject);
}
}
?>
Loops while/ for/ foreachmethod (NOT binary safe; case-sensitive)
环路while/ for/foreach方法(不是二进制安全的;区分大小写)
Now of course besides all of those functions you can also use a simple loop to loop through the string and replace each search => replacepair which you have.
现在当然除了所有这些函数之外,您还可以使用一个简单的循环来遍历字符串并替换search => replace您拥有的每一对。
But this gets way more complex when you do it binary safe, case-insensitive and for multidimensional arrays than just using the functions above. So I won't include any examples here.
但是,当您对二进制安全、不区分大小写和多维数组进行操作时,这比仅使用上述函数要复杂得多。所以我不会在这里包含任何例子。
Affected String
受影响的字符串
Right now all methods shown above do the replacement over the entire string. But sometimes you want to replace something only for a certain part of your string.
现在上面显示的所有方法都会替换整个字符串。但有时您只想为字符串的某个部分替换某些内容。
For this you probably want to/can use substr_replace(). Or another common method is to use substr()and apply the replacement only on that particular substring and put the string together afterwards. Of course you could also modify your regex or do something else to not apply the replacement to the entire string.
为此,您可能想要/可以使用substr_replace(). 或者另一种常用方法是substr()仅在该特定子字符串上使用和应用替换,然后将字符串放在一起。当然,您也可以修改正则表达式或执行其他操作以不将替换应用于整个字符串。
回答by NekaraNef
str_replace is sufficient for simple replacement jobs (such as replacing a single letter), but the use of preg_replace is generally advised (if you want something more flexible or versatile), because it's flexible and versatile. And as the 'a' is just an example...:
str_replace 对于简单的替换工作(例如替换单个字母)就足够了,但通常建议使用 preg_replace(如果您想要更灵活或更通用的东西),因为它灵活且通用。因为'a'只是一个例子......:
$String = preg_replace('/<string>/','<replacement>',$String);
Or if you want multiple replacements at once:
或者,如果您想一次更换多个:
$String = preg_replace(array('/<string 1>/','/<string 2>/'),array('<replacement 1>','<replacement 2>'),$String);
preg_replace can, unfortunately, be quite tricky to use. I recommend the following reads: http://php.net/manual/en/function.preg-replace.phphttp://www.phpro.org/tutorials/Introduction-to-PHP-Regex.html
不幸的是,preg_replace 使用起来非常棘手。我建议阅读以下内容:http: //php.net/manual/en/function.preg-replace.phphttp://www.phpro.org/tutorials/Introduction-to-PHP-Regex.html
Also, if you decide to use str_replace(), and your replacement needs to be case-sensitive, you're going to need str_ireplace().
此外,如果您决定使用 str_replace(),并且您的替换需要区分大小写,那么您将需要 str_ireplace()。
回答by sivi
This can work also without of any of PHP string functions, here changing your 'a' to '&' ampersand character:
这也可以在没有任何 PHP 字符串函数的情况下工作,这里将您的 'a' 更改为 '&' &符号字符:
for ($i=0; $i<strlen($str); $i++){
if ($str[$i] == 'a'){
$str[$i] = '&';
}
}
echo $str;
回答by sandeep kumar
Use function preg_replace()
使用函数 preg_replace()
$text ='this is the old word';
echo $text;
echo '<br>';
$text = preg_replace('/\bold word\b/', 'NEW WORD', $text);
echo $text;

