1

I wrote this script to do this but there is an issue I couldn't figure out:

$buffer = '<a href="http://wwww.domain.com">Domain1</a>';
$buffer .= '<a href="http://wwww.domain.com?id=2">Domain2</a>';

preg_match_all('/<a href="(.*?)"/s', $buffer, $matches);

$searches = array();
$replaces = array();

foreach($matches[1] as $link){

    $contain = parse_url($link, PHP_URL_QUERY);

    $symbol = $contain ? "&" : "?";

    $new_link = $link . $symbol . "mode=testing";

    $searches[] = $link;

    $replaces[] = $new_link;

}
$newbuffer = str_replace($searches ,$replaces , $buffer);

var_dump($newbuffer);

Output:

<a href="http://wwww.domain.com?mode=testing">Domain1</a>
<a href="http://wwww.domain.com?mode=testing?id=2">Domain2</a>

Expected Output thats adding the parameter to each link:

<a href="http://wwww.domain.com?mode=testing">Domain1</a>
<a href="http://wwww.domain.com?id=2&mode=testing">Domain2</a>

Any help?

1 Answer 1

1

The problem comes from:

  • $searches contains :
array(2) {
  [0]=>
  string(24) ""http://wwww.domain.com""
  [1]=>
  string(29) ""http://wwww.domain.com?id=2""
}
  • $replaces contains:
array(2) {
  [0]=>
  string(37) ""http://wwww.domain.com?mode=testing""
  [1]=>
  string(42) ""http://wwww.domain.com?id=2&mode=testing""
}

Then str_replace replaces all elements from $searches to all elements from $replaces, so, http://wwww.domain.com with http://wwww.domain.com?mode=testing AND http://wwww.domain.com?id=2 with http://wwww.domain.com?mode=testing?id=2 (it append ?mode=testing after domain.com)

Here is a solution:

Add " arround the links in both arrays.

$buffer = '<a href="http://wwww.domain.com">Domain1</a>';
$buffer .= '<a href="http://wwww.domain.com?id=2">Domain2</a>';

preg_match_all('/<a href="(.*?)"/s', $buffer, $matches);

$searches = array();
$replaces = array();

foreach($matches[1] as $link){
    $contain = parse_url($link, PHP_URL_QUERY);
    $symbol = $contain ? "&" : "?";
    $new_link = $link . $symbol . "mode=testing";
    $searches[] = '"' . $link . '"';
    $replaces[] = '"' . $new_link . '"';
}
$newbuffer = str_replace($searches ,$replaces , $buffer);
var_dump($newbuffer);

Output:

<a href="http://wwww.domain.com?mode=testing">Domain1</a>
<a href="http://wwww.domain.com?id=2&mode=testing">Domain2</a>
Sign up to request clarification or add additional context in comments.

1 Comment

Aww amazing @toto, its working perfectly !!, i spent 1 week trying to solve this problem :p

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.