如何使用preg_replace剥离字符,但仅当它位于包装器中时


How to use preg_replace to strip a character but only when it is within a wrapper

>我需要从用户提供的输入中删除 ' 和 "(单引号和双引号),但前提是它在左括号和右括号 [ ] 内......我不想从字符串中剥离任何其他内容。

所以这个:

[字体大小="10"]

需要更改为

[字体大小=10]

但是这个:

[字体大小=10]牛说"哞哞"[/字体]

不会剥离任何东西。

这:

[字体大小="10"]牛说"哞哞"[/字体]

将更改为:

[字体大小=10]牛说"哞哞"[/字体]

感谢您的任何帮助...

你可以这样做:

$result = preg_replace('~(?>'[|'G(?<!^)[^]"'']++)'K|(?<!^)'G["'']~', '', $string);

解释:

(?>            # open a group
    '[         # literal [
  |            # OR
    'G(?<!^)   # contiguous to a precedent match but not at the start of the string
    [^]"'']++  # all that is not quotes or a closing square bracket
)'K            # close the group and reset the match from results
|              # OR
(?<!^)'G["'']  # a contiguous quote

使用此模式时,仅替换引号,因为括号内的所有其他内容都将从匹配结果中删除。

我想到的快速变体(注意PHP 5.3语法):

$s = preg_replace_callback('/(''[[^'']]+])/', function ($match) {
        return str_replace(['"', ''''], ['', ''], $match[1]);
    }, $s);

您的情况非常简单;(:

<?php
$str1 = '
[font size="10"]
needs to change to
[font size=10]
but this:
[font size=''10''] my single quoted size is ''OK?''
[font size=10]The cow says "moo"[/font]
would not strip anything.
This:
[font size="10"]The cow says "moo"[/font]
would change to this:
[font size=10]The cow says "moo"[/font]
';
//
$str1 = preg_replace('/=[''"]'s?([^''"]*)'s?[''"]/', '=$1', $str1);
echo "<pre>";
echo $str1;
echo "</pre>";
?>    

使用的正则表达式:

=[''"]'s?([^''"]*)'s?[''"]

带有等号 = 的字符串开头,后跟双引号/单引号,前面有空格或不

...