也许不能像我想的那样解决这个问题,但是也许你们可以帮助我。
我的产品名称里有很多畸形字。
有些符号的前面是(
,后面是)
,或者是其中之一,对于/
和"
符号也是一样的。
我所做的就是把产品的名字用空格隔开,并检查这些单词。
所以我想把它们替换成零。但是,硬盘驱动器可以是40GB ATA 3.5" hard drive
。我需要处理所有的单词,但是我不能对3.5"
使用与()
或//
相同的方法,因为这个3.5"
是有效的。
所以我只需要替换引号,当它在字符串的开始和字符串的结束。
$cases = [
'(testone)',
'(testtwo',
'testthree)',
'/otherone/',
'/othertwo',
'otherthree/',
'"anotherone',
'anothertwo"',
'"anotherthree"',
];
$patterns = [
'/^'(/',
'/')$/',
'~^/~',
'~/$~',
//Here is what I can not imagine, how to add the rule for `"`
];
$result = preg_replace($patterns, '', $cases);
这是很好的工作,但它可以在一个regex_replace()
?如果有,有人能帮我弄清楚报价的模式吗?
引号的结果应该是这样的:
'"anotherone', //no quote at end leave the leading
'anothertwo"', //no quote at start leave the trailin
'anotherthree', //there are quotes on start and end so remove them.
您可以使用另一种方法:而不是定义一个模式数组,使用基于一个单一的替换的regex:
preg_replace('~^[(/]|[/)]$|^"(.*)"$~s', '$1', $s)
查看regex演示
:
-
^[(/]
-字符串 开头的 -
|
-或 -
[/)]$
-字符串 末尾的 -
|
-或 -
^"(.*)"$
—字符串开头的"
,然后捕获到组1中的任何0+字符(由于/s
选项,.
也匹配换行序列)和字符串末尾的"
。
(
或/
字面值)
或/
字量替换模式为$1
,匹配前2个选项时为空,匹配第3个选项时包含组1值。
注意:如果您需要替换直到没有找到匹配,请将preg_match
与preg_replace
一起使用(参见演示):
$s = '"/some text/"';
$re = '~^[(/]|[/)]$|^"(.*)"$~s';
$tmp = '';
while (preg_match($re, $s) && $tmp != $s) {
$tmp = $s;
$s = preg_replace($re, '$1', $s);
}
echo $s;
可以了
preg_replace([[/(]?(.+)[/)]?|/'"(.+)'"/], '$1', $string)