tags:

views:

77

answers:

4

I'm trying to write a regular expression in PHP. From this code I want to match 'bar'.

<data info="foo">
  "bar"|tr
</data>

I tried this two regex, without success. It matches 'foo"> "bar'.

$regex = '/"(.*?)"\|tr/s';
$regex = '/"[^"]+(.*?)"\|tr/s';

Anyone can help me?

Thank you.

A: 
\"\w+\"

should match any word char in parenthesis

slf
I would match also "bar foobar"|tr and not a single word. Thanks for your answer.
Alessandro Astarita
+3  A: 

You need to escape the backslash in PHP strings:

$regex = '/"([^"]*)"\\|tr/s';

I added a capturing group to get the contents of the quotes, which you seem to be interested in.

Since you seem to apply the regex to XML, I just want to warn you that XML and regular expressions don't play well together. Regex is only recommendable in conjunction with a DOM.

Tomalak
Thank you so much. It works.
Alessandro Astarita
You are welcome.
Tomalak
A: 

Try this:

$regex = '/"([^">]+)"\|tr/s'

If you want to match just letters and numbers, you can do:

$regex = '/"([\w\d]+)"\|tr/s'
Julio Greff
Thank you, it works too...
Alessandro Astarita
A: 
$regex = '/"(.+?)"(?=\|tr)/'

Will match "bar" (including the quotes), and you have the bar string (without quotes) in $1. Uses look-ahead.

streetpc
Thank you too...
Alessandro Astarita