PHP: Return string between two characters

后端 未结 4 1480
余生分开走
余生分开走 2020-12-30 07:09

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 sear

相关标签:
4条回答
  • 2020-12-30 07:24

    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

    0 讨论(0)
  • 2020-12-30 07:30

    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*');
    
    0 讨论(0)
  • 2020-12-30 07:39
    <?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"
    }
    
    0 讨论(0)
  • 2020-12-30 07:47

    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
    
    0 讨论(0)
提交回复
热议问题