tags:

views:

47

answers:

2

Hello,

I have some trouble with regex and php here:

   <span style="color: blue">word1</span> word by word by word <span style="color: red">word</span>

I'm trying to get word1 out. Is the regex the best way though? Need to process around 70 sencences like this.

UPDATE

$one = '<span style="color: blue">word1</span> word by word by word <span style="color: red">word</span>';
preg_match('/<span[^>]*>(.*?)<\/span>/',$one);
echo $one;

Don't works, it outputs the same. Am I doing something wrong?

Thanks

A: 
var str = '<span style="color: blue">word1</span> word by word by word <span style="color: red">word</span>
';

var myArray = str.match(/<span[^>]+>(\w+)<\/span>/);

Return myArray[1] = "word1";

unigg
What if the opening tag is just `<span>`? What if the contents are empty? What if the words contain non-word characters?
quantumSoup
In my case, there's never just <span> (color varies from red and blue), no empty ones, but sometimes they contain two words.
c4rrt3r
+3  A: 

Using the following regex, capture the first result and discard the rest (if you just want to get the first result).

 <span[^>]*>(.*?)<\/span>

See it in action: http://rubular.com/r/ateGVj5PCu


WARNING: Regex is not suited for parsing HTML. If your code is more complicated than this, I strongly recommend using an (X)HTML parser

quantumSoup
+1 for "Regex is not suited for parsing HTML." Truer words have not been spoken.
Kivin