正则表达式用于匹配 php 之间的短语



我想匹配''(单引号(中的内容。例如:'for example'应返回forexample。这只是我必须分析的句子的一部分,我用了preg_split(s)来表示整个句子,所以'for example'会变得'for and example'

现在我已经尝试了/^'(.*)|(.*)'$/,它只返回for而不返回example,如果我像/^(.*)'|'(.*)$/这样说,它只返回example而不返回for。我应该如何解决这个问题?

您可以通过利用G元字符继续匹配单引号内无限数量的空格分隔字符串来避免字符串的双重处理。

代码: (PHP 演示( (正则表达式演示(

$string = "text 'for an example of the "continue" metacharacter' text";
var_export(preg_match_all("~(?|'|G(?!^) )K[^ ']+~", $string, $out) ? $out[0] : []);

输出:

array (
0 => 'for',
1 => 'an',
2 => 'example',
3 => 'of',
4 => 'the',
5 => '"continue"',
6 => 'metacharacter',
)

要获取单个句子(然后要拆分(,您可以使用 preg_match_all(( 捕获两个单引号之间的任何内容。

preg_match_all("~'([^']+)'~", $text, $matches)
$string = $matches[1];

$string现在包含类似"带单词的示例字符串"的内容。 现在,如果要根据特定的序列/字符拆分字符串,可以使用 explode((:

$string = "example string with words";
$result = explode(" ", $string);
print_r($result);

给你:

Array
(
[0] => example
[1] => string
[2] => with
[3] => words
)

最新更新