0

Im newbie, I have some ploblem with PHP str_replace and I need to advice

$a = '<a class="class1 clss2" href="http://www.somedomain.com/page1.php" target="_blank"><p class="myclass">';

I want to replace html tag like this

Before:

<a class="class1 clss2" href="http://www.somedomain.com/page1.php" target="_blank"><p class="myclass">

After:

<p class="myclass"><a class="class1 clss2" href="http://www.somedomain.com/page1.php" target="_blank">

I try to coding and I have problem with dynamic value in class="..." and href="..."

Please advice and thank :)

Andy Lester
  • 91,102
  • 13
  • 100
  • 152
  • 1
    Regexes on HTML can be very hard, depending on how flexible they need to be. When you say "like", what parts can vary? – cmbuckley Mar 27 '14 at 19:49
  • 1
    You should use DOMDocument or similar DOM manipulation tools to do this. – Mike Brant Mar 27 '14 at 19:51
  • **Don't use regular expressions to parse HTML. Use a proper HTML parsing module.** You cannot reliably parse HTML with regular expressions, and you will face sorrow and frustration down the road. As soon as the HTML changes from your expectations, your code will be broken. See http://htmlparsing.com/php or [this SO thread](http://stackoverflow.com/questions/3577641/how-do-you-parse-and-process-html-xml-in-php) for examples of how to properly parse HTML with PHP modules that have already been written, tested and debugged. – Andy Lester Mar 27 '14 at 20:01

1 Answers1

0

Below code is only suitable for your sample that you provided in the question:

This is using preg_replace() instead of str_replace():

$a = '<a class="class1 clss2" href="http://www.somedomain.com/page1.php" target="_blank"><p class="myclass">';
$a = preg_replace("|(<a [^>]*>)(<p [^>]*>)|", "$2$1", $a);
print "$a\n";

Here using regex i am capturing the two tags in two groups $1 and $2. And during replace I am just swapping their places like $2$1.

Sabuj Hassan
  • 38,281
  • 14
  • 75
  • 85