Php 匹配有限数量的空格,忽略标记中的空格

Php 匹配有限数量的空格,忽略标记中的空格,php,regex,xml,pcre,Php,Regex,Xml,Pcre,我试图创建一个与输入的最后五个“单词”匹配的正则表达式,其中“单词”被定义为与[^]+或[^]*]*>[^]*>[^]*匹配的任何东西(因此任何东西都用空格分隔,但将之间的空格作为字母计数) 我试过这个: /([^ ]+(?:(?<!<[^>]+) +(?![^<]*>)(?:.*?)){0,4})$/ /([^]+(?:(?]+)+(?![^)(?:.*){0,4})$/ 但它给了我一个错误,即回望必须是固定长度的 假设我有以下字符串: 'It\'s just

我试图创建一个与输入的最后五个“单词”匹配的正则表达式,其中“单词”被定义为与
[^]+
[^]*]*>[^]*>[^]*
匹配的任何东西(因此任何东西都用空格分隔,但将
之间的空格作为字母计数)

我试过这个:

/([^ ]+(?:(?<!<[^>]+) +(?![^<]*>)(?:.*?)){0,4})$/
/([^]+(?:(?]+)+(?![^)(?:.*){0,4})$/
但它给了我一个错误,即回望必须是固定长度的

假设我有以下字符串:

'It\'s just that he <span class="verb">appear</span>ed rather late.'
“只是他来得太晚了。”
应该匹配

'that he <span class="verb">appear</span>ed rather late.'
他出现得相当晚 一个简单的方法:

preg_match('~^(?:\s*[^>\s]*(?:>[^<]*<[^>\s]*)*){0,5}~', strrev(rtrim($str)), $m);
$result = strrev($m[0]);

preg\u match('~^(?:\s*[^>\s]*(?:>[^我认为您的解决方案已经非常接近了。请查看此解决方案:

$str = 'It\'s just that he <span class="verb">appear</span>ed rather late.';
$reg = '/(([^ ]*<[^>]*>[^ ]*)+|[^ ]+)/'; // let me know if you need explanation
if (preg_match_all($reg, $str, $m)) { // "_all" to match more than one
    $m = array_slice($m[0], -5, 5, true); // last 5 words
    //$m = implode(' ', $m); // uncomment this if you want a string instead of array
    print_r($m);
}
$str='只是他出现得太晚了';
$reg='/(([^]*]*>[^]*)+|[^]+)/';//如果您需要解释,请告诉我
如果(preg_match_all($reg,$str,$m)){/“_all”匹配多个
$m=array_slice($m[0],-5,5,true);//最后5个字
//$m=内爆(“”,$m);//如果需要字符串而不是数组,请取消对此的注释
印刷费(百万美元);
}
返回:

Array
(
    [2] => that
    [3] => he
    [4] => <span class="verb">appear</span>ed
    [5] => rather
    [6] => late.
)
数组
(
[2] =>那
[3] =>他
[4] =>出现
[5] =>相当于
[6] =>迟到了。
)

请添加一个或多个示例字符串和预期的输出。一种方法是
而(preg_-match('/]*/',$input))$input=preg_-replace('/(]*/','$1'.“\0”,$input);
preg_-match('/(?:(?:[^]+){0,4}[^]*$/',$input,$input);
$input=str(“\0”,““”);
但是如果您不知道,如果在输入框中出现使用的字符(\0),那么这看起来相当粗糙,可能会破坏一些东西-请看这里的顶部答案::-)出于某种原因这里需要纯正则表达式吗?首先使用
strip\u tags()
函数,然后输入“words”不是更容易吗甚至是
explode()
string?不错的主意,SilentDariusz,但是标记需要保留。这返回
span class=“verb”>出现得很晚。
Nice。适用于我的特定情况。如果有任何嵌套的标记(例如,如果出现了类似
的东西,则可能不起作用),但幸运的是,我不是这样。对。事实上,可能会有更多问题。记住: