Page 1 of 1

Matching "^" through regular expression in preg_match_all

Posted: Thu Apr 02, 2009 3:17 pm
by daskas
pickle | Please use [ code=php ], [ code=text ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.


I want the following code to match strings such as [[^A]], [[^ABC]], [[ABC]], etc. i.e.,strings in double brackets that may have 0 or more ^ in the beginning with alpha characters following. Then return the values in the double brackets, i.e., ^A, ^ABC, ABC.

However, somehow the PHP code below does not work for matching the ^. Where is the error?

Michael.

Code: Select all

function myData ($text) { //text passed in  
  preg_match_all("/\[\[(\^*\w+)\]\]/", $text, $matches);
  foreach ($matches[1] as $val) {
      $text = preg_replace ("/\[\[$val\]\]/",getData($val),$text);  
  }
  return $text;
}

pickle | Please use [ code=php ], [ code=text ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.

Re: Matching "^" through regular expression in preg_match_all

Posted: Thu Apr 02, 2009 4:16 pm
by Christopher
You might want to make it a character set (of one) [\^]

Re: Matching "^" through regular expression in preg_match_al

Posted: Thu Apr 02, 2009 7:26 pm
by McInfo
Try this:

Code: Select all

<?php
$string = '[[ABC]][[^WER]]Skip[[^G]]Outside';
preg_match_all('/\[\[\\^*\w+\]\]/', $string, $matches);
foreach ($matches[0] as $match)
{
    $matches[1][] = preg_replace('/\[\[|\]\]/', '', $match);
}
echo '<pre>'; print_r($matches); echo '</pre>';
?>
Output is:

Code: Select all

<pre>Array
(
    [0] => Array
        (
            [0] => [[ABC]]
            [1] => [[^WER]]
            [2] => [[^G]]
        )
 
    [1] => Array
        (
            [0] => ABC
            [1] => ^WER
            [2] => ^G
        )
 
)
</pre>
Edit: This post was recovered from search engine cache.

Re: Matching "^" through regular expression in preg_match_all

Posted: Thu Apr 02, 2009 9:25 pm
by daskas
Thank you very much for your help. It worked!