0

Say you have a dynamic string gotten from an ajax call. As example this is one response:

$string = '<div>
    <a href="http://somelink" class="possible-class">text</a>
    <a href="http://anotherlink">other text</a>
</div>';

How can you modify all the href urls in the string to be the result of another method, such as this example method:

function modify_href( $href ) {
  return $href . '/modified';
}

so then the resulting string is:

$string = '<div>
    <a href="http://somelink/modified" class="possible-class">text</a>
    <a href="http://anotherlink/modified">other text</a>
</div>';
Sometip
  • 332
  • 1
  • 10

3 Answers3

0

Without further information for what you need it, this is one of the way.

$string = '<div>
    <a href="'.modify_href('http://somelink').'" class="possible-class">text</a>
    <a href="'.modify_href('http://anotherlink').'">other text</a>
</div>';

function modify_href( $href ) {
  return $href . '/modified';
}

echo $string;
Universus
  • 386
  • 1
  • 13
0

To call a function with the regex matches you can use the function preg_replace_callback http://php.net/manual/en/function.preg-replace-callback.php. something like:

function modify_href( $matches ) {
      return $matches[1] . '/modified';
}

$result = preg_replace_callback('/(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)/', 'modify_href', $string);

I havent tested this, but I think it should work. I got the regex from here: https://rushi.wordpress.com/2008/04/14/simple-regex-for-matching-urls/

Tim
  • 401
  • 4
  • 11
0

It is not recommended to parse html with regex.

You might use DomDocument and createDocumentFragment

function modify_href( $href ) {
    return $href . '/modified';
}

$string = '<div>
    <a href="http://somelink" class="possible-class">text</a>
    <a href="http://anotherlink">other text</a>
</div>';

$doc = new DomDocument();
$fragment = $doc->createDocumentFragment();
$fragment->appendXML($string);
$doc->appendChild($fragment);
$xpath = new DOMXPath($doc);
$elements = $xpath->query("//div/a");
foreach ($elements as $element) {
    $element->setAttribute("href", modify_href($element->getAttribute("href")));
}
echo $doc->saveHTML();

Demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70