PHP preg_match get in between string

后端 未结 5 1885
广开言路
广开言路 2020-12-18 20:44

I\'m trying to get the string hello world.

This is what I\'ve got so far:

$file = \"1232#hello world#\";

preg_match(\"#1232\\#(.*)\\##\         


        
相关标签:
5条回答
  • 2020-12-18 21:10
    preg_match('/1232#(.*)#$/', $file, $match);
    
    0 讨论(0)
  • 2020-12-18 21:16

    It is recommended to use a delimiter other than # since your string contains #, and a non-greedy (.*?) to capture the characters before #. Incidentally, # does not need to be escaped in the expression if it is not also the delimiter.

    $file = "1232#hello world#";
    preg_match('/1232#(.*?)#/', $file, $match);
    
    var_dump($match);
    // Prints:
    array(2) {
      [0]=>
      string(17) "1232#hello world#"
      [1]=>
      string(11) "hello world"
    }
    

    Even better is to use [^#]+ (or * instead of + if characters may not be present) to match all characters up to the next #.

    preg_match('/1232#([^#]+)#/', $file, $match);
    
    0 讨论(0)
  • 2020-12-18 21:20

    Use lookarounds:

    preg_match("/(?<=#).*?(?=#)/", $file, $match)
    

    Demo:

    preg_match("/(?<=#).*?(?=#)/", "1232#hello world#", $match);
    print_r($match)
    

    Output:

    Array
    (
        [0] => hello world
    )
    

    Test it here.

    0 讨论(0)
  • 2020-12-18 21:22

    What if you want the delimiter to also be included in the array, this would be more usefull for preg_split where you might not want each array element to begin and end with the delimiters, the example im about to show would would include the delimeters inside the array values. this would be what you would need preg_match('/\#(.*?)#/', $file, $match); print_r($match); this would output array( [0]=> #hello world# )

    0 讨论(0)
  • 2020-12-18 21:32

    It looks to me like you just have to get $match[1]:

    php > $file = "1232#hello world#";
    php > preg_match("/1232\\#(.*)\\#/", $file, $match);
    php > print_r($match);
    Array
    (
        [0] => 1232#hello world#
        [1] => hello world
    )
    php > print_r($match[1]);
    hello world
    

    Are you getting different results?

    0 讨论(0)
提交回复
热议问题