1

我有一个大文本:

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 一词。

4

1 回答 1

5

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

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
}
于 2013-06-25T09:33:35.240 回答