0

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

c4rrt3r
  • 612
  • 2
  • 7
  • 18

2 Answers2

3

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

Community
  • 1
  • 1
quantumSoup
  • 27,197
  • 9
  • 43
  • 57
0
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
  • 466
  • 3
  • 8
  • What if the opening tag is just ``? What if the contents are empty? What if the words contain non-word characters? – quantumSoup Aug 21 '10 at 23:19
  • In my case, there's never just (color varies from red and blue), no empty ones, but sometimes they contain two words. – c4rrt3r Aug 22 '10 at 00:09