dongle0396 2019-07-09 10:52
浏览 54
已采纳

问题正则表达模式寻找类似匹配

I have one of the four patter:

"Test"
'Test'
`Test`
(Test)

Is it possible to get "Test" with a single preg_match call?

I tried the following:

if ( preg_match( '/^(?:"(.*)"|\'(.*)\'|`(.*)`|\((.*)\')$/iu', $pattern, $matches ) )

... but this gives me five elements of $matches back. But I would like to have two only (One for the whole match and one for the found match with "Test" in it.)

  • 写回答

4条回答 默认 最新

  • douying9296 2019-07-09 11:01
    关注

    You can use dot to match the characters aroun d the word and use array_unique to remove duplicates.

    preg_match_all("/.(\w+)./", $str,$match);
    foreach($match as &$m) $m = array_unique($m);
    
    var_dump($match);
    

    https://3v4l.org/T2hnh

    array(2) {
      [0]=>
      array(4) {
        [0]=>
        string(6) ""Test""
        [1]=>
        string(6) "'Test'"
        [2]=>
        string(6) "`Test`"
        [3]=>
        string(6) "(Test)"
      }
      [1]=>
      &array(1) {
        [0]=>
        string(4) "Test"
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波