views:

523

answers:

3

I am wanting to use "keywords" within a large string. These keywords start and end using *my_keyword* and are user defined. How, within a large string, can I search and find what is between the two * characters and return each instance?

The reason it might change it, that parts of the keywords can be user defined, such as *page_date_Y* which might show the year in which the page was created.

So, again, I just need to do a search and return what is between those * characters. Is this possible, or is there a better way of doing this if I don't know the "keyword" length or what i might be?

+10  A: 
<?php
// keywords are between *
$str = "PHP is the *best*, its the *most popular* and *I* love it.";    
if(preg_match_all('/\*(.*?)\*/',$str,$match)) {            
        var_dump($match[1]);            
}
?>

Output:

array(3) {
  [0]=>
  string(4) "best"
  [1]=>
  string(12) "most popular"
  [2]=>
  string(1) "I"
}
codaddict
Brilliant! And so simple. Thank you!
Nic Hubbard
A: 

Here ya go:

function stringBetween($string, $keyword)
{
    $matches = array();
    $keyword = preg_quote($keyword, '~');

    if (preg_match_all('~' . $keyword . '(.*?)' . $keyword . '~s', $string, $matches) > 0)
    {
        return $matches[1];
    }

    else
    {
        return 'No matches found!';
    }
}

Use the function like this:

stringBetween('1 *a* 2 3 *a* *a* 5 *a*', '*a*');
Alix Axel
A: 

Explode on "*"

$str = "PHP is the *best*, *its* the *most popular* and *I* love it.";
$s = explode("*",$str);
for($i=1;$i<=count($s)-1;$i+=2){
    print $s[$i]."\n";    
}

output

$ php test.php
best
its
most popular
I
ghostdog74