【问题标题】:Get words before and after string with whitespace使用空格获取字符串前后的单词
【发布时间】:2018-03-05 21:56:11
【问题描述】:

我正在尝试使用正则表达式在特定单词之后检索 5 个单词。我的代码如下。

$str= '<li>111-37774 Blue</li><li>111-1566 Red</li><li>122-4555 White</li><li>1455-789 Yellow</li></ul>Minimum order applies. This is a string for testing.<p>';
$regexForPattern ='/((?:\w+\W\s*){0,5})minimum\b((?:\W*\w+){0,5})/i';   
preg_match_all ($regexForPattern , trim( preg_replace('#<[^>]+>#', ' ', $str) ), $patternMatches); 
print_r($patternMatches);

我想要来自$str 的“最小”一词前后各 5 个词。

目前我得到的输出是:

Array ( [0] => 
    Array ( [0] => 4555 White 1455-789 Yellow Minimum order applies. This is a ) 
            [1] => Array ( [0] => 4555 White 1455-789 Yellow ) 
            [2] => Array ( [0] => order applies. This is a ) 
)

我希望结果数组中的字符串 122-4555 White 1455-789 Yellow 而不是 4555 White 1455-789 Yellow。对于像 1455-789 这样的词,它会将 1455 视为一个词,而将 789 视为另一个词。我怎样才能只得到确切的词?

谁能帮我解决这个问题?提前致谢。

【问题讨论】:

  • 可能你想用(?:\S+\s+){0,5}(?:\W*\w+){0,5}替换(?:\w+\W\s*){0,5}(?:\s+\S+){0,5}
  • 您也可以使用 SELECT SUBSTRING_INDEX 将其推回 SQL 层 - 对您来说可能更简单,请参阅以下资源 - stackoverflow.com/questions/3471199/…
  • 顺便说一句,这是一个正则表达式小提琴 - regex101.com/r/NRJCSz/1
  • @WiktorStribiżew..谢谢..它的工作。

标签: php regex


【解决方案1】:

\w 无法匹配数字之间的-,因此正则表达式无法从预期位置获取预期的子字符串。

您应该将(?:\w+\W\s*){0,5} 替换为(?:\S+\s+){0,5},并将(?:\W*\w+){0,5} 替换为(?:\s+\S+){0,5}

'~((?:\S+\s+){0,5})minimum\b((?:\s+\S+){0,5})~'

请参阅regex demo

这样,您将匹配关键字前后的任何 0 到 5 个空格分隔的非空白块。

PHP demo

$str= '<li>111-37774 Blue</li><li>111-1566 Red</li><li>122-4555 White</li><li>1455-789 Yellow</li></ul>Minimum order applies. This is a string for testing.<p>';
$regexForPattern ='/((?:\S+\s+){0,5})minimum\b((?:\s+\S+){0,5})/i';   
$nstr = trim( preg_replace('#<[^>]+>#', ' ', $str));
echo $nstr . "\n";
preg_match_all ($regexForPattern , $nstr, $patternMatches); 
print_r($patternMatches);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    • 2013-01-15
    • 2013-09-07
    • 1970-01-01
    相关资源
    最近更新 更多