【问题标题】:Regex search: word with open ending正则表达式搜索:带有开放式结尾的单词
【发布时间】:2016-04-28 04:53:45
【问题描述】:

我有一个值如下的数组:

$needles = array(
    'hide',
    'foo',
    'bar'
);

我想在这样的字符串中搜索这些针:

$string = 'lets unhide this div';

foreach( $needles as $needle ):

    if( strpos( $string, $needle ) ) echo 'do stuff';

endforeach;

到目前为止,这工作得很好,但存在一个问题,即上面示例中的取消隐藏被捕获但它不应该被捕获。我知道我可以简单地在针周围添加空白,但事情是这样的:

搜索应捕获以该开头的单词(隐藏而不是unhide),但应使单词的结尾保持打开状态,以便捕获隐藏ous .. . 这在我知道的英语中可能没有意义,但这正是我需要的行为(因为它在德语中效果很好)。

所以我需要这样的正则表达式:

if( strpos( preg_match( 'stringstartorwhitespace|'.$needle.'|anythingexceptwhitespace|whitespace' ), $string ) ) echo 'do stuff';

以下是一些结果

schön in schön = 1
schön in unschön = 0
schön in schönes = 1
schön in schönstes = 1
schön in schönem = 1

【问题讨论】:

  • 我觉得你需要this

标签: php regex search


【解决方案1】:

在我理解之前,您需要word boundary,它表示为\b。正则表达式将是

\bschön

Regex Demo

PHP 代码

$re = "/\\bschön/"; 
$str = array("schön", "unschön", "schönes", "schönstes", "schönem");

foreach ($str as $x) {
    if (preg_match($re, $x)) {
        print($x."\n");
    }
}

Ideone Demo

【讨论】:

  • @Grandy 不用担心..不要忘记接受和支持
  • Jep ...只是想在我投票之前在我的应用程序中尝试一下;)
  • 我真的应该进入正则表达式,但它太复杂了._.
  • 哈!我开始多次阅读这个主题......使用正则表达式唯一喜欢的是它是如此强大=P
猜你喜欢
  • 2018-02-21
  • 1970-01-01
  • 2012-02-23
  • 1970-01-01
  • 2011-10-13
  • 2020-01-25
  • 2012-03-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多