Search code examples
phppreg-replacepreg-match

exclude all except from preg_match


If I have a string like

$string = 'the grey fox [[function name]] jumped over the moon';

How do I remove everything from the string except what is found in the square brackets? I can find and replace the code inside the square brackets like so:

$page_function = preg_replace('#\[\[(.*?)\]\]#', '', $string);

I need a way to inverse the preg_replace so I can replace all EXCEPT the code found in the preg_replace.

Thanks!


Solution

  • What you are most likely looking for is the complement function preg_match http://php.net/manual/en/function.preg-match.php

    Example from interactive shell:

    php > $string = 'the grey fox [[function name]] jumped over the moon';
    php > preg_match('#\[\[(.*?)\]\]#', $string, $m);
    php > var_dump($m);
    array(2) {
      [0]=>
      string(17) "[[function name]]"
      [1]=>
      string(13) "function name"
    }