2

I have the following string:

keyword|title|http://example.com/

I would like to use the PHP function

preg_match_all ( $anchor, $key, $matches, PREG_SET_ORDER) )

currently

$anchor='/([\w\W]*?)\|([\w\W]*)/';

and I get $matches array:

Array
(
    [0] => Array
        (
            [0] => keyword|title|http://example.com/
            [1] => keyword
            [2] => title|http://example.com/
        )

)

I would like to get

matches[1]=keyword
matches[2]=title
matches[3]=http://example.com

How would I have to modify $anchor to achieve this?

2
  • You just need to add one more \|([\w\W]*?) in your regex. Commented Apr 12, 2011 at 21:12
  • Thank you, this worked. Final expression: $anchor='/([\w\W]*?)\|([\w\W]*?)\|([\w\W]*)/'; Commented Apr 12, 2011 at 21:52

2 Answers 2

6

The easiest way would be to use explode() instead of regular expressions:

$parts = explode('|', $str);

Assuming none of the parts can contain |. But if they could, regex wouldn't help you much either.

Sign up to request clarification or add additional context in comments.

2 Comments

Absolutely. Just for the sake of it... heres a regex that would work: /([^|]+)/
Gary, this is matches if I use this regex: <pre>Array ( [0] => Array ( [0] => keyword [1] => keyword ) [1] => Array ( [0] => title [1] => title ) [2] => Array ( [0] => example.com [1] => example.com ) ) </pre>
1

If you want to keep using the regex to avoid a manual loop, then I'd recommend this over the used [\w\W]* syntax and for readability:

$anchor = '/([^|]*) \| ([^|]*) \| ([^\s|]+)/x';

It's a bit more robust with explicit negated character classes. (I assume neither title nor url can contain | here.)

2 Comments

Hey mario, thank you, this worked. I know nothing about the regex expressions; they look like gibberish to me. Where could i find the rules and mechanics of these expressions? Thank you
Yes. They are sort of a programming language of their own. It takes time to get accustomed to them. regular-expressions.info provides a mostly understandable introduction. And here are some tools that can sometimes help in constructing regular expressions: stackoverflow.com/questions/89718/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.