【问题标题】:Find a pattern in a string在字符串中查找模式
【发布时间】:2022-01-07 08:28:42
【问题描述】:

我正在尝试检测以下模式中的字符串:[url('example')] 以替换该值。

我曾想过使用正则表达式来获取方括号内的字符串,然后使用另一个来获取括号内的文本,但我不确定这是否是最好的方法。

//detect all strings inside brackets
preg_match_all("/\[([^\]]*)\]/", $text, $matches);

//loop though results to get the string inside the parenthesis
preg_match('#\((.*?)\)#', $match, $matches);
    

【问题讨论】:

  • 试试这个:(?<=\[url\(')[^']+(?='\)\])

标签: php regex


【解决方案1】:

要匹配括号之间的字符串,您可以使用单个模式来获取匹配项:

\[url\(\K[^()]+(?=\)])

模式匹配:

  • \[url\(匹配[url(
  • \K清除当前匹配缓冲区
  • [^()]+ 匹配除 () 之外的 1+ 个字符
  • (?=\)]) 正向前瞻,向右断言 )]

查看regex demo

例如

$re = "/\[url\(\K[^()]+(?=\)])/";
$text = "[url('example')]";
if (preg_match($re, $text, $match)) {
    var_dump($match[0]);;
}

输出

string(9) "'example'"

另一个选项可能是使用捕获组。您可以将' 放在组内或组外以捕获值:

\[url\(([^()]+)\)]

查看另一个regex demo

例如

$re = "/\[url\(([^()]+)\)]/";
$text = "[url('example')]";
if (preg_match($re, $text, $match)) {
    var_dump($match[1]);;
}

输出

string(9) "'example'"

【讨论】:

    猜你喜欢
    • 2020-09-06
    • 1970-01-01
    • 2014-06-28
    • 2014-11-18
    • 2016-10-02
    • 1970-01-01
    • 2014-03-24
    • 2020-11-26
    相关资源
    最近更新 更多