Resitive
Resitive

Reputation: 370

Search string for sentence/word

I have a large text:

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. 

What would be the easiest way to search the string and return the word inbetween the apostrophe marks?

So far i've tried this:

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


foreach($findme as $needle){

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

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

I know there's always the word find right before the apostrophe.

Upvotes: 1

Views: 1417

Answers (1)

Aleks G
Aleks G

Reputation: 57346

Why not just use regex?

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

UPDATE: If string "find" is not fixed, you can use a variable in its place, moreover, you can separate multiple words easily:

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

Upvotes: 5

Related Questions