Matching "^" through regular expression in preg_match_all

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
daskas
Forum Newbie
Posts: 2
Joined: Thu Apr 02, 2009 3:14 pm

Matching "^" through regular expression in preg_match_all

Post 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.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Matching "^" through regular expression in preg_match_all

Post by Christopher »

You might want to make it a character set (of one) [\^]
(#10850)
User avatar
McInfo
DevNet Resident
Posts: 1532
Joined: Wed Apr 01, 2009 1:31 pm

Re: Matching "^" through regular expression in preg_match_al

Post 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.
Last edited by McInfo on Mon Jun 14, 2010 12:26 pm, edited 1 time in total.
daskas
Forum Newbie
Posts: 2
Joined: Thu Apr 02, 2009 3:14 pm

Re: Matching "^" through regular expression in preg_match_all

Post by daskas »

Thank you very much for your help. It worked!
Post Reply