0

I need to catch custom "tag" in text string, rewrite and replace it. It looks like:

<mytag=http://url.com/file.php?some=variable&another=variable>

First I need to catch url from tag, then I rewrite it with my function and then replace whole tag with new url. Can anybody help me how to catch and replace it? In text can be more tags with various url's.

stix
  • 812
  • 2
  • 7
  • 22
  • You should check the documentation for preg_replace[http://php.net/manual/en/function.preg-replace.php ]. Also: What have you tried?[http://mattgemmell.com/2008/12/08/what-have-you-tried/ ] – FrankieTheKneeMan Nov 15 '12 at 18:33
  • Please refrain from parsing HTML with RegEx as it will [drive you į̷̷͚̤̤̖̱̦͍͗̒̈̅̄̎n̨͖͓̹͍͎͔͈̝̲͐ͪ͛̃̄͛ṣ̷̵̞̦ͤ̅̉̋ͪ͑͛ͥ͜a̷̘͖̮͔͎͛̇̏̒͆̆͘n͇͔̤̼͙̩͖̭ͤ͋̉͌͟eͥ͒͆ͧͨ̽͞҉̹͍̳̻͢](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454). Use an [HTML parser](http://stackoverflow.com/questions/292926/robust-mature-html-parser-for-php) instead. – Madara's Ghost Nov 15 '12 at 18:37

2 Answers2

0

You can try this:

    $my_tag = "<mytag=http://url.com/file.php?some=variable&another=variable>";
    preg_match( "/<mytag=(.*)>/", $my_tag, $matches );
    $new_tag = str_replace( $matches[1], "http://newurl.com", $my_tag);

The $new_tag variable will end up with the following:

<mytag=http://newurl.com>
andrux
  • 2,782
  • 3
  • 22
  • 31
0

That's trivial. You have enough context and anchors for that. And basically using preg_replace or preg_repace_callback (for more complex replacement schemes) works as follows:

$src = preg_replace('~  <mytag=  (http://[^>]+)  >  ~smix', '<a href=$1>$1</a>', $src);

The whitespace here are decorative. Crucial is the [^>] for not matching to much, and ( and ) for capturing the URL as $1.

Community
  • 1
  • 1
mario
  • 144,265
  • 20
  • 237
  • 291