Php 搜索句子/单词的字符串

Php 搜索句子/单词的字符串,php,string,search,Php,String,Search,我有一个大文本: 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

我有一个大文本:

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这个词。

为什么不直接使用regex呢

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
}

为什么不直接使用正则表达式呢

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
}

一个人曾经试图用正则表达式解决一个问题。“然后他有两个,”尼尔斯基伦杰说,“坦率地说,我不理解你的评论的相关性。他在字符串中寻找特定的匹配项——这就是正则表达式的作用。如果你知道你在做什么,那么你将解决一个问题,而不是制造更多的问题。如果我正确理解了这个问题,
find
字符串是可配置的或依赖于环境的,否则为什么要使用数组呢。因此字符串也可能包含有问题的单词,因此需要转义等。如果OP对regexp了解得足够多,他可能已经选择了这个解决方案,所以显然他没有,这可能会导致很多问题。此外,regexp在计算上比简单的
strpo
调用要昂贵得多。我主要是想说应该避免使用正则表达式,除非它们是迄今为止最好的解决方案。如果它是可配置的,那么只需使用一个变量即可。@restive如果您有多个静态“查找”工作,您可以使用正则表达式一次性匹配它们-请参阅my updateA man曾经尝试用正则表达式修复一个问题。“然后他有两个,”尼尔斯基伦杰说,“坦率地说,我不理解你的评论的相关性。他在字符串中寻找特定的匹配项——这就是正则表达式的作用。如果你知道你在做什么,那么你将解决一个问题,而不是制造更多的问题。如果我正确理解了这个问题,
find
字符串是可配置的或依赖于环境的,否则为什么要使用数组呢。因此字符串也可能包含有问题的单词,因此需要转义等。如果OP对regexp了解得足够多,他可能已经选择了这个解决方案,所以显然他没有,这可能会导致很多问题。此外,regexp在计算上比简单的
strpo
调用要昂贵得多。我主要是想说应该避免使用正则表达式,除非它们是迄今为止最好的解决方案。如果它是可配置的,那么只需使用一个变量即可。@restive如果您有多个静态“查找”工作,您可以使用正则表达式一次性匹配它们-请参阅我的更新