tags:

views:

694

answers:

3

Hi! Is there a way to put a wildcard in a string? The reason why I am asking is because currently I have a function to search for a substring between two substrings (i.e grab the contents between "my" and "has fleas" in the sentence "my dog has fleas", resulting in "dog").

function get_string_between($string, $start, $end){ 
    $string = " ".$string; 
    $ini = strpos($string,$start); 
    if ($ini == 0) return ""; 
    $ini += strlen($start); 
    $len = strpos($string,$end,$ini) - $ini; 
    return substr($string,$ini,$len); 
} 

What I want to do is have it search with a wildcard in the string. So say I search between "%WILDCARD%" and "has fleas" in the sentence "My dog has fleas" - it would still output "dog".

I don't know if I explained it too well but hopefully someone will understand me :P. Thank you very much for reading!

+1  A: 

Use a regex.

$string = "My dog has fleas";
if (preg_match("/\S+ (\S+) has fleas/", $string, $matches))
  echo ($matches[1]);
else
  echo ("Not found");

\S means any non-space character, + means one or more of the previous thing, so \S+ means match one or more non-space characters. (…) means capture the content of the submatch and put into the $matches array.

KennyTM
+2  A: 

This is one of the few cases where regular expressions are actually helpful. :)

if (preg_match('/my (\w+) has/', $str, $matches)) {
    echo $matches[1];
}

See the documentation for preg_match.

Lukáš Lalinský
That's just ignorant, regular expressions are excellent tools.
Raveren
A: 

If you insist to use wildcard (and yes, PREG is much better) you can use function fnmatch which works only on *NIX.

Cheers

confiq