-1

How can I use preg_replace to do this:

I want to replace:

<a href="index.php?option=example1&view=something">

with this

<a href="index.php?option=example2&view=somethingelse&task=task1">

Thanx

Yannis
  • 912
  • 2
  • 14
  • 34
  • You might want to look into HTML parsers for complex html replacing cases, eg. php's dom lib (http://www.php.net/dom) – kjetilh Aug 14 '11 at 17:01
  • possible duplicate of [Grabbing the href attribute of an A element](http://stackoverflow.com/questions/3820666/grabbing-the-href-attribute-of-an-a-element) – Gordon Aug 14 '11 at 17:13
  • *(related)* [Replace values in a URI query string](http://stackoverflow.com/questions/3777481/replace-values-in-a-uri-query-string/3777523#3777523) – Gordon Aug 14 '11 at 17:15

2 Answers2

1

you could do:

$url = '<a href="index.php?option=example1&view=something">';

$getInside = preg_match('/<a href=\"(.*)\">/', $url, $match);
$parse = parse_url($match[1]);

$newUrl = $parse['path']."?";
$urlArray = array();

parse_str($parse['query'], $params);

foreach($params as $key => $match){ 
    if($key == 'option'){
        $urlArray['option'] = 'example2';
    }
    if($key == 'view'){
        $urlArray['view'] = 'somethingelse';
    }
}
$urlArray['task'] = 'task1';
$newUrl .= http_build_query($urlArray, '', '&'); 
Mihai Iorga
  • 39,330
  • 16
  • 106
  • 107
0

This will replace

<a href="index.php?option=example1&view=something">

by

<a href="index.php?option=example2&view=somethingelse&task=task1">

:

preg_replace('#<a href="index\.php\?option=example1&view=something">#', '<a href="index.php?option=example2&view=somethingelse&task=task1">', $string);
Arnaud Le Blanc
  • 98,321
  • 23
  • 206
  • 194