This is a discussion on need help for regex within the PHP Language forums, part of the PHP Programming Forums category; Hi, I need a regex (may be together with a php function) to retrieve information within '[' and ']' in a line ...
|
|||||||
| FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read |
|
|||
|
Hi,
I need a regex (may be together with a php function) to retrieve information within '[' and ']' in a line of text. Here is an example: hello world, example [demo|123] line with some [$55] yesys [no]. I need to retrieve all the three pieces of text enclosed in [] pairs. Thanks in advance! Alex Shi -- ================================================== Cell Phone Batteries at 30-50%+ off retail prices! http://www.pocellular.com ================================================== |
|
|||
|
Alex Shi wrote:
> I need a regex (may be together with a php function) to retrieve > information within '[' and ']' in a line of text. Here is an example: > > hello world, example [demo|123] line with some [$55] yesys [no]. > > I need to retrieve all the three pieces of text enclosed in [] pairs. $foo = 'hello world, example [demo|123] line with some [$55] yesys [no].'; preg_match_all("/\[(.*)\]/U", $foo, $matches); print_r($matches); This gives you: Array ( [0] => Array ( [0] => [demo|123] [1] => [$55] [2] => [no] ) [1] => Array ( [0] => demo|123 [1] => $55 [2] => no ) ) -- Chris Hope The Electric Toolbox - http://www.electrictoolbox.com/ |
|
|||
|
Alex Shi wrote:
> I need a regex (may be together with a php function) to retrieve > information within '[' and ']' in a line of text. Here is an example: > > hello world, example [demo|123] line with some [$55] yesys [no]. > > I need to retrieve all the three pieces of text enclosed in [] pairs. // retrieve data $string = "hello world, example [demo|123] line with some [$55] yesys [no]."; preg_match_all('~\[([^\]]*)\]~', $string, $matches); // look at the result print_r($matches); // print all values foreach ($matches[1] as $value) { echo($value . '<br>'); } // access first value echo($matches[1][0] . '<br>'); // access third value echo($matches[1][2] . '<br>'); Regards, Matthias |
|
|||
|
> Alex Shi wrote:
> > > I need a regex (may be together with a php function) to retrieve > > information within '[' and ']' in a line of text. Here is an example: > > > > hello world, example [demo|123] line with some [$55] yesys [no]. > > > > I need to retrieve all the three pieces of text enclosed in [] pairs. > > $foo = 'hello world, example [demo|123] line with some [$55] yesys [no].'; > preg_match_all("/\[(.*)\]/U", $foo, $matches); > print_r($matches); > > This gives you: > Array > ( > [0] => Array > ( > [0] => [demo|123] > [1] => [$55] > [2] => [no] > ) > > [1] => Array > ( > [0] => demo|123 > [1] => $55 > [2] => no > ) > > ) > > > -- > Chris Hope > The Electric Toolbox - http://www.electrictoolbox.com/ Thanks! Alex Shi |