0

I'm trying to extract the following in php, but my regex or egreg is out of place and i got really confused. Please help me put these to two variables:

  <a onmouseover="dgsa.sm(this)" onmouseout="dgsa.hm();" href="http://www.cnn.com/testpage.html#page_mostview">test titles</a>

I want the variable:

$url="http://www.cnn.com/testpage.html#page_mostview";
$title="test titles";

Any kind of help on this is greatly appreciated.

John Conde
  • 212,985
  • 98
  • 444
  • 485
thevoipman
  • 1,672
  • 2
  • 17
  • 41

1 Answers1

0

If you have in one big string:

<?php
$str = '<a href="ABC.jpg">Hello</a>  <a href="DEF.jpg">Bye</a>';
$expr = '/<a[^>]*? href=\"(?<url>[^\"]+)\"[^>]*?>(?<text>.*?)<\/a>/';
echo preg_match_all($expr, $str, $amatches);
echo '<br><br>';
print_r($amatches);
?>

You can also use:

preg_match_all($expr, $str, $amatches, PREG_SET_ORDER);

Which may suit better (I ofen prefer this approach)

If you have in spearate strings and handle in a loop, use preg_match instead. Tis will only return the first, and you loop.


Edit: here it is with your example, as requested.

<?php

$str = '<a onmouseover="dgsa.sm(this)" onmouseout="dgsa.hm();" href="http://www.cnn.com/testpage.html#page_mostview">test titles</a>';

$expr = '/<a[^>]*? href=\"(?<url>[^\"]+)\"[^>]*?>(?<text>.*?)<\/a>/';

echo preg_match_all($expr, $str, $amatches, PREG_OFFSET_CAPTURE);

echo '<br><br>';

print_r($amatches);

?>
Robbie
  • 17,323
  • 4
  • 33
  • 71
  • I have been trying the past few hours and I can't seem to get it to do what I want. Can you please help revised your answer with my examples? It will definitely help me learn. – thevoipman Aug 09 '12 at 14:11
  • No - that's not giving troubles. I've simply pasted in your string, as requested. Tested and works a treat. So check what you're copying / pasting. – Robbie Aug 09 '12 at 23:49