Php 转义除标记'外的匹配引号;s属性

Php 转义除标记'外的匹配引号;s属性,php,regex,escaping,Php,Regex,Escaping,我想转义匹配的引号,但标记属性中的引号除外,例如: 输入: xyz <test foo='123 abc' bar="def 456"> f00 'escape me' b4r "me too" but not this </tEsT> blah 'escape " me' 返回: xyz <test foo=\'123 abc\' bar=\"def 456\"> f00 \'escape me\' b4r \"me too\" but not this

我想转义匹配的引号,但标记属性中的引号除外,例如:

输入:

xyz <test foo='123 abc' bar="def 456"> f00 'escape me' b4r "me too" but not this </tEsT> blah 'escape " me'
返回:

xyz <test foo=\'123 abc\' bar=\"def 456\"> f00 \'escape me\' b4r \"me too\" but not this </tEsT> blah \'escape " me\'
xyz f00“逃离我”b4r“我也是”,但不是这个废话“逃离我”
现在我想使用regexp零宽度负数look-behind跳过前面有等号的匹配引号:

$result = preg_replace('/((?<=[^=])([\'"])((\\\2|.)*?)\2)/', "\\\\$2$3\\\\$2", $input);

$result=preg_replace('/(?向前看,而不是向后看来建立上下文,向前看。通常更容易

$result = preg_replace('/([\'"])(?![^<>]*>)((?:(?!\1).)*)\1/',
                       '\\\\$1$2\\\\$1',
                        $subject);
$result=preg\u replace('/([\'”)(?![^]*>)((?:(?!\1)。*)\1/,
'\\\\$1$2\\\\$1',
$subject);
(['“])#捕获开放式报价
(?![^]*>)#确保它不在标签内
(#捕捉到下一个报价之前的所有内容
(?:#…测试每个字符后
(?!\1 |[])。#…当然不是开场白
)*#…或角括号
)
\1#匹配与第一个相同类型的另一个报价
我假设属性值中没有任何尖括号。

这里是另一个

$str = "xyz <test foo='123 abc' bar=\"def 456\"> f00 'escape me' b4r \"me too\" but not this <br/> <br/></tEsT> blah 'escape \" me'";

$str_escaped = preg_replace_callback('/(?<!\<)[^<>]+(?![^<]*\>)/','escape_quotes',$str);
// check all the strings outside every possible tag
// and replace each by the return value of the function below

function escape_quotes($str) {
    if (is_array($str)) $str = $str[0];
    return preg_replace('/(?<!\\\)(\'|")/','\\\$1',$str);
    // escape all the non-escaped single and double quotes
    // and return the escaped block
}
$str=“xyz f00‘逃出我’b4r‘我也是’,但这不是什么‘逃出我’;
$str_escaped=preg_replace_回调('/(?]+(?![^)/','escape_quotes',$str);
//检查每个可能标记之外的所有字符串
//并用下面函数的返回值替换每个
函数转义引号($str){
如果(is_数组($str))$str=$str[0];

return preg_replace('/(?不要用正则表达式执行此操作。您会后悔的。它对我非常有效!感谢您的详细解释:)你在哪里学得这么好的正则表达式?@Artur:主要是通过阅读、练习和在论坛上闲逛获得的。:d有人能验证一下这是否适用于所有情况吗?我假设所有的符号都被转义(分别转义到
),而不是标记周围的符号。
xyz <test foo='123 abc\' bar="def 456"> f00 \'escape me\' b4r "me too" but not this </tEsT> blah \'escape " me'
$result = preg_replace('/([\'"])(?![^<>]*>)((?:(?!\1).)*)\1/',
                       '\\\\$1$2\\\\$1',
                        $subject);
$str = "xyz <test foo='123 abc' bar=\"def 456\"> f00 'escape me' b4r \"me too\" but not this <br/> <br/></tEsT> blah 'escape \" me'";

$str_escaped = preg_replace_callback('/(?<!\<)[^<>]+(?![^<]*\>)/','escape_quotes',$str);
// check all the strings outside every possible tag
// and replace each by the return value of the function below

function escape_quotes($str) {
    if (is_array($str)) $str = $str[0];
    return preg_replace('/(?<!\\\)(\'|")/','\\\$1',$str);
    // escape all the non-escaped single and double quotes
    // and return the escaped block
}