所以 - 我有这样的字符串(string1 示例):
'aaaaabbbbbcccccword'
'aaaaabbbbbcccccwor*d'
'aaaaabbbbbcccccw**ord*'
'aaaaabbbbbccccc*word*'
我需要从这些字符串的末尾删除一些子字符串(string2)以及string2中的任何*字符以及*前面的字符串2和后面的字符串2。 字符串 2 是某个变量。我想不出可以在这里使用的正则表达式。
//wrong example, * that might happen to be inside of $string1 are not removed :(
$string1 = 'aaaaabbbbbcccccw**ord*';
$string2 = 'word';
$result = preg_replace('#'*?' . $string2 . ''*?$#', '', $string1);
有人可以为此建议一个 PCRE 正则表达式吗?
附言我可以在列表 15 分中获得点赞吗?所以我可以投票给人们吗?
这是一种方法:
$string1 = 'aaaaabbbbbcccccw**ord*';
$string2 = 'word';
$result = preg_replace('#'*?' . implode(''**', str_split($string2)) . ''*?$#', '',
$string1);
echo $result;
//=> aaaaabbbbbccccc
$regexp = '#'**' . implode(''**', str_split($string2)) . ''**$#';
$result = preg_replace($regexp, '', $string1);
演示
str_split
将字符串拆分为字符,然后implode
在每个字符之间插入'**
。然后我们在它之前和之后放置'**
,以抓取周围的任何*
字符。