dsa5233 2014-07-25 08:56
浏览 347
已采纳

如何在此正则表达式匹配中忽略引号中的字符串?

How can I ignore instances of the string "or" when it is inside single/double quotes?

The current expression is /^(?=\$)(.+?)(?:\s+or\s+)(.+?)$/s

Test value 1: $test or "default value"

Test value 2: $errors->has('email') ? 'error or failure' : ''

Test value 1 should be affected, but value 2 should be unaffected.

Test script:

Update $expression to test.

<?php

function issetDefaults($value) {

    // Original expression with the issue
    //$expression = '/^(?=\$)(.+?)(?:\s+or\s+)(.+?)$/s';

    // @Avinash Raj's version; almost there; failing on test 2
    $expression = '/([\'"])(?:(?!\1).)*or(?:(?!\1).)*\1(*SKIP)(*F)|^(\S+) or ([\'"].*[\'"])/';
    return preg_replace($expression, 'isset($2) ? $2 : $3', $value);
}

// Tests
$tests = array(

    // should be affected
    '$test or "default value"',
    '$age or 90',

    // shouldn't be affected
    'myfunc(\'foo or bar\')',
    '$errors->has(\'email\') ? \'error or failure\' : \'\'',
    '$errors->has("email") ? "error or failure" : ""',
    '$errors->has("email") ? "error \'or\' failure" : ""'
);


// Output tests
foreach ($tests as $key => $test) {
    $num = $key+1;
    echo '<strong>Original Value '.$num.'</strong>';
    echo '<pre>'.print_r($test,true).'</pre>';

    echo '<strong>Value '.$num.' after function</strong>';
    echo '<pre>'.print_r(issetDefaults($test),true).'</pre>';

    echo '<hr />';
}
  • 写回答

1条回答 默认 最新

  • dpkpaxhzffixp8426 2014-07-25 09:05
    关注

    The below regex would matches the string or which was not enclosed within single or double quotes,

    (['"])(?:(?!\1).)*or(?:(?!\1).)*\1(*SKIP)(*F)|\bor\b
    

    Replace or with whatever string you want.

    DEMO

    Explanation:

    • (['"]) Captures ' or " symbols.
    • (?:(?!\1).)* Matches any character not the one which was captured into the first group zero or more times.
    • or Matches the string or.
    • (?:(?!\1).)* Matches any character not the one which was captured into the first group zero or more times.
    • \1 First captured group was referred through back referencing.
    • (*SKIP)(*F) Makes the whole match to fail and the characters which are following | symbol(\bor\b) would be matched from the remaining part.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 arduino控制ps2手柄一直报错
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题