繁体   English   中英

在字符串中搜索句子/单词

[英]Search string for sentence/word

我有一句话:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse tempor 
faucibus eros. Fusce ac lectus at risus pretium tempor. Curabitur vulputate 
eu nibh at consequat. find'someword' Curabitur id ipsum eget massa condimentum pulvinar in 
ac purus. Donec sollicitudin eros ornare ultricies tristique. find'someword2' Sed condimentum 
eros a ante tincidunt dignissim. 

搜索字符串并在撇号之间返回单词的最简单方法是什么?

到目前为止,我已经尝试过了:

$findme = array('find');
$hay = file_get_contents('text.txt');


foreach($findme as $needle){

    $search = strpos($hay, $needle);

    if($search !== false){
        //Return word inbetween apostrophe
    }
}

我知道在撇号之前总是有find一词。

为什么不只使用正则表达式?

if(preg_match_all("/find'(.+?)'/", $hay, $matches)) {
    array_shift($matches);
    print_r($matches);
}
else {
    //no matches
}

更新:如果字符串“ find ”不是固定的,则可以在其位置使用变量,此外,可以轻松分隔多个单词:

$prefix = "find|anotherword";
if(preg_match_all("/($prefix)'(.+?)'/", $hay, $matches)) {
    $matches = $matches[2];
    print_r($matches);
}
else {
    //no matches found
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM