0

I have the following code. I am trying to get everything inside the "a" tags. At the moment it is working. I am getting “first” and “second” as an output. opening "a" tag and closing "a" tag are in the same line.

$v = 'this is test 
<a href="products.html">first</a> 
<a>second</a;
preg_match_all("#<a\b[^>]*>(.*?)</a>#", $v, $foo);
echo implode("\n", $foo[1]);

But if I write the following way,

$v = '<a href="products.html">first
</a> 
preg_match_all("#<a\b[^>]*>(.*?)</a>#", $v, $foo);
echo implode("\n", $foo[1])';

here i moved the closing "a" tag to the second line and now It's not giving me any output. Does anyone know how to make it work?

Santi .
  • 93
  • 1
  • 8

1 Answers1

1

As for the problem you are having, it is because you need to enable the single line option (s):

preg_match_all("#<a\b[^>]*>(.*?)</a>#s", $v, $foo);

Otherwise . does not match a line break.

Explanation of the option from the documentation:

If this modifier is set, a dot metacharacter in the pattern matches all characters, including newlines. Without it, newlines are excluded.

But you probably would be better off not using a regex. See this question for other approaches in PHP.

Community
  • 1
  • 1