12

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?

codaddict
  • 445,704
  • 82
  • 492
  • 529
Nic Hubbard
  • 41,587
  • 63
  • 251
  • 412
  • I found a super nice function that does just what I want, but, I want to put all the found keywords into an array. http://www.justin-cook.com/wp/2006/03/31/php-parse-a-string-between-two-strings/ Does anyone have tips on how I could modify that script? – Nic Hubbard Jan 12 '10 at 07:24
  • I hope the user can't define a keyword with a * in it ;) – zombat Jan 12 '10 at 07:26
  • I am using the function in the above link u have given and its working fine for me.... – Avinash Jan 12 '10 at 07:30
  • You might find [`s($str)->between('*', '*')`](https://github.com/delight-im/PHP-Str/blob/8fd0c608d5496d43adaa899642c1cce047e076dc/src/Str.php#L412) helpful, as found in [this standalone library](https://github.com/delight-im/PHP-Str). – caw Jul 27 '16 at 03:28

4 Answers4

42
<?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
  • 445,704
  • 82
  • 492
  • 529
3

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
  • 327,991
  • 56
  • 259
  • 343
0

If you want to extract a string that's enclosed by two different strings (Like something in parentheses, brackets, html tags, etc.), here's a post more specific to that:

Grabbing a String Between Different Strings

Community
  • 1
  • 1
jtrick
  • 1,329
  • 18
  • 23
0

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
  • 151,645
  • 95
  • 393
  • 500