使用正则表达式找到一个短语多达16个字符?(php)


Use regex to find a phrase UP TO 16 characters? (php)

我遇到了点小问题。我有一个很长的字符串,里面有很多单词,我想把它分开,但是字符串的大多数部分都有一个静态的开始和结束,但是这个只有一个结束,我想要得到的字符串的实际位是动态的,但它最多有16个字符,它可以更少,这个短语中的单词数量是未知的。

的例子:

Name: John Smith Occupation: Doctor Currently Busy Gender: Male 

我想获得"当前忙碌"在它自己没有得到另一个字符串的结束之前。

但是我也想使用相同的代码从这个字符串中获得"Not Yet Here":

Name: John Smith Occupation: Doctor Not Yet Here Gender: Male 

我找不到一个方法,我甚至不知道是否可能,所以希望这里有人能帮助我。

您的问题可能是RegEx无法解决的。如果"occupation"的值可以是一个或多个单词,它的后面直接跟着另一个值,这个值可以是一个或多个单词,那么作为一个人,你会如何区分这两个短语?

我希望至少,你有一组已知的Occupation值。如果是这种情况,那么您可以这样编写表达式:

(?<=Doctor |Nurse ).*(?= Gender)

(?<=...)(?=...)位是向后看和向前看断言,本质上说"确保表达式Doctor |Nurse出现在匹配的短语之前(但不匹配它的那一部分),并且表达式Gender出现在匹配的短语之后(但也不匹配它的那一部分)。"

查看实际效果:http://regexr.com?34buq

不是最优雅的方式,但这里有一个解决方案:

$string = 'Name: John Smith Occupation: Doctor Currently Busy Gender: Male';
$groups = array_filter(preg_split('/'s?'w+:'s?/', $string));
// Split by ['s? => optional space]['w+ => characters a-zA-Z0-9_][:]['s? => optional space]
// $groups[2] contains 'Doctor Currently Busy'
$pieces = explode(' ', $groups[2]);
$pieces = array_reverse($pieces);
$length = 0;$i = 0;$c = count($pieces);$result = array(); // We need this for the loop
// $c and $i are to preserve the first word if the length of all words are < 16 !
foreach($pieces as $piece){
    $length += strlen($piece);
    $i++;
    if($length <= 16 && $c != $i){
        $result[] = $piece;
    }else{
        break;
    }
}
$result = array_reverse($result);
$final_result = implode(' ', $result);
echo $final_result; // Currently Busy