简体   繁体   English

在php中查找条件并将其替换为条件

[英]Find and replace string with condition in php

I am newbie in PHP. 我是PHP的新手。 I want to replace certain characters in a string. 我想替换字符串中的某些字符。 My code is in below: 我的代码在下面:

$str="this 'is' a new 'string and i wanna' replace \"in\" \"it here\"";             
$find = [
        '\'', 
        '"'                
    ];

$replace = [
        ['^', '*']
        ['@', '#']                
    ];

$result = null;
$odd = true;
for ($i=0; $i < strlen($str); $i++) {
    if (in_array($str[$i], $find)) {
        $key = array_search($str[$i], $find);
        $result .= $odd ? $replace[$key][0] : $replace[$key][1];
        $odd = !$odd;
    } else {
        $result .= $str[$i];
    }
}            
echo $result;

the output of the above code is: 上面代码的输出是:
this ^is* a new ^string and i wanna* replace @in# @it here# . this ^is* a new ^string and i wanna* replace @in# @it here#

but I want the output to be: 但我希望输出是:
this ^is* a new 'string and i wanna' replace @in# "it here" . this ^is* a new 'string and i wanna' replace @in# "it here"

That means character will replace for both quotation(left quotation and right quotation- condition is for ' and "). for single quotation, string will not be replaced either if have left or right quotation. it will be replaced for left and right quotation. 这意味着字符将同时替换为两个引号(左引号和右引号,条件为'和“)。对于单引号,如果具有左引号或右引号,则字符串将不会被替换;将被替换为左引号和右引号。

Ok, I don't know what all that code is trying to accomplish. 好的,我不知道所有这些代码都试图完成什么。

But anyway here is my go at it 但是无论如何,这是我的努力

$str = "this 'is' a new 'string and i wanna' replace \"in\" \"it here\"";

$str = preg_replace(["/'([^']+)'/",'/"([^"]+)"/'], ["^$1*", "@$1#"], $str, 1);

print_r($str);

You can test it here 你可以在这里测试

Ouptput 输出量

this ^is* a new 'string and i wanna' replace @in# "it here"

Using preg_replace and a fairly simple Regular expression, we can replace the quotes. 使用preg_replace和一个相当简单的正则表达式,我们可以替换引号。 Now the trick here is the fourth parameter of preg_replace is $count And is defined as this: 现在的诀窍是,preg_replace的第四个参数是$count并定义为:

count If specified, this variable will be filled with the number of replacements done. count如果指定,此变量将填充完成的替换次数。

Therefore, setting this to 1 limits it to the first match only. 因此,将此值设置为1只能将其限制为第一个匹配项。 In other words it will do $count replacements, or 1 in this case. 换句话说,它将执行$count替换,在这种情况下为1 Now because it's an array of patterns, each pattern is treated separately. 现在,因为它是模式阵列,所以每个模式都将被单独处理。 So each one is basically treated as a separate operation, and thus each is allowed $count matches, or each get 1 match/replacement. 因此,基本上每个人都被视为一个单独的操作,因此每个人都可以进行$count匹配,或者每个人获得1个匹配/替换。

Now rather or not this fits every use case you have I cannot say, but it's the most straight forward way to do it for the example you provided. 现在,这是否适合您我不能说的每个用例,但这是针对您提供的示例进行操作的最直接的方法。

As for the match itself /'([^']+)'/ 至于比赛本身/'([^']+)'/

  • / opening and closing "delimiters" for the Expression (its a required thing, although it doesn't have to be / ) /为表达式打开和关闭“定界符”(它是必需的,尽管不一定是/
  • ' literal match, matches ' one time (the opening quote) '文字匹配,匹配'一次(开头引号)
  • ( ... ) capture group (group1) so we can use it in the replacement, as $1 ( ... )捕获组(group1),因此我们可以在替换组中使用它,例如$1
  • [^']+ character set with a [^ not modifier, match anything not in the set, so anything that is not a ' one or more times, greedy [^']+带有[^ not修饰符的字符集,匹配集合中未包含'所有内容,因此所有非'一次或多次,贪婪的内容
  • ' literal match, matches ' one time (the ending quote) '文字匹配,匹配'一次(结尾引号)

The replacement "^$1*" 替换"^$1*"

  • ^ literal, adds this char in ^文字,在此字符中添加
  • $1 use the contents of the capture group (group1) $1使用捕获组(group1)的内容
  • * literal, adds the char in *文字,在其中添加字符

Hope that helps understand how it works. 希望能帮助您了解其工作原理。

UPDATE 更新

Ok I think I finally deciphered what you want: 好吧,我想我终于破译了你想要的东西:

string will be replaced for if any word have left and right quotation. 如果有任何单词用左引号和右引号替换,则将替换字符串。 example..'word'..here string will be changed..but 'word...in this case not change or word' also not be changed. 例如..'word'..此处字符串将被更改..但'word ...在这种情况下不更改或单词'也不会更改。

This seems like you are trying to say only "whole" words with no spaces. 似乎您正在尝试只说“整个”字,没有空格。

So in that case we have to adjust our regular expression like this: 因此,在这种情况下,我们必须像这样调整正则表达式:

 $str = preg_replace(["/'([-\w]+)'/",'/"([-\w]+)"/'], ["^$1*", "@$1#"], $str);

So we removed the limit $count and we changed what is in the character group to be more strict: 因此,我们删除了限制$count并更改了字符组中的字符以使其更加严格:

  • [-\\w]+ the \\w means the working set, or in other words a-zA-Z0-9_ then the - is a literal (it has to/should go first in this case) [-\\w]+ \\w表示工作集,换句话说a-zA-Z0-9_-是文字(在这种情况下,它必须/应该先行)

What we are saying with this is to match only strings that start and end with a quote(single|double) and only if the string within them match the working set plus the hyphen. 我们所说的是仅匹配以引号(single | double)开头和结尾的字符串,并且前提是其中的字符串与工作集加连字符匹配。 This does not include the space. 这不包括空格。 This way in the first case, your example, it produces the same result, but if you were to flip it to 在第一种情况下,以这种方式,您的示例将产生相同的结果,但是如果将其翻转为

 //[ORIGINAL] this 'is' a new 'string and i wanna' replace \"in\" \"it here\"
 this a new 'string and i wanna' replace  'is' \"it here\" \"in\"

You would get his output 你会得到他的输出

this a new 'string and i wanna' replace  ^is* \"it here\" @in#

Before this change you would have gotten 在进行此更改之前,您将获得

this a new ^string and i wanna* replace  'is' @it here# "in"

In other words it would have only replaced the first occurrence, now it will replace anything between the quotes if and only if it's a whole word. 换句话说,它将仅替换第一个出现的词,而现在且仅当它是一个完整的单词时,它将替换引号之间的所有内容。

As a final note you can be even more strict if you only want alpha characters by changing the character set to this [a-zA-Z]+ , then it will match only a to z , upper or lower case. 最后一点,你可以更加严格,如果你只通过更改字符集本想字母字符[a-zA-Z]+ ,那么它只会匹配azupperlower的情况。 Whereas the example above will match 0 to 9 (or any combination of them) the - hyphen, the _ underline and the previously mentioned alpha sets. 而以上示例将匹配09 (或它们的任意组合)的-连字符, _下划线和前面提到的alpha集。

Hope that is what you need. 希望那是您所需要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM