Re: Regex to catch <p>s

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Ryan S wrote:
Hey!

Thansk for replying!

<clip>
It is obvious I haven't had my caffeine yet. This is my last try to get the pattern straight:

<?php

$html = <<<END_OF_HTML

<b>hello</b>
<b class="blah">hello</b>
<p>those</p>
<p class="blah">hello</p>
<a>hello</a>
<a href="url">this</a>
<a>rose</a>
<a href="regex yo">hello</a>
<a>nose</a>
<a id="2" href="regex yo">hello</a>
<p>that</p>
<p class="blah" title="whatever">hello</p>
END_OF_HTML;

$tags = array();
$tags[] = 'p';
$tags[] = 'a';

$attr = array();
$attr[] = 'class';
$attr[] = 'href';

$vals = array();
$vals[] = 'blah';
$vals[] = 'url';
$vals[] = 'yo';

$text = array();
$text[] = 'hello';
$text[] = 'this';
$text[] = 'that';

$tags = implode('|', $tags);
$attr = implode('|', $attr);
$vals = implode('|', $vals);
$text = implode('|', $text);

$pattern = '/<('.$tags.')[^>]*('.$attr.')?[^>]*('.$vals.')?[^>]*>('.$text.')[^<\/]*<\/\1>/i';

echo $pattern."\n";
echo "--------------------\n";

preg_match_all($pattern, $html, $matches);

var_dump($matches);

?>
</clip>

I dont get why you added this
$tags[] = 'a';

Does that mean I will have to make tags like that for all the html tags that i think will be on the page?

Hi,

I said before that the example could be a little bit overkill, but it gives a quick example how to find any tag(s) given, with any attribute(s) given and with any text given in between the opening and closing tag.

And yes, it might be incomplete or maybe not even accurate, but it does give you a headstart on your solution. There always will be people who will give you a shorter, cleaner, more beautiful example, but I hope that it was helpful for you or will be helpful for someone else.

Cheers,

Aschwin Wesselius


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux