php - How to change the href (url) in a link (a) element? -


here full link.

<a href="http://localhost/mysite/client-portal/">client portal</a> 

i want above link following.

<a href="#popup">client portal</a> 

i don't know how work preg_replace done.

preg_replace('\/localhost\/mysite\/client-portal\/', '#popup', $output) 

if link can achieve goal str_replace():

<?php  $link = '<a href="http://localhost/mysite/client-portal/">client portal</a>'; $href = 'http://localhost/mysite/client-portal/'; $new_href = '#popup';  $new_link = str_replace($href, $new_href, $link);  echo $new_link;  ?> 

output:

<a href="#popup">client portal</a> 

if want can use dom:

<?php  $link = '<a href="http://localhost/mysite/client-portal/">client portal</a>'; $new_href = '#popup';  $doc = new domdocument; $doc->loadhtml($link);  foreach ($doc->getelementsbytagname('a') $link) {    $link->setattribute('href', $new_href); }  echo $doc->savehtml();  ?> 

output:

<!doctype html public "-//w3c//dtd html 4.0 transitional//en" "http://www.w3.org/tr/rec-html40/loose.dtd"> <html><body><a href="#popup">client portal</a></body></html> 

or can use preg_replace() this:

<?php  $link = '<a href="http://localhost/mysite/client-portal/">client portal</a>'; $new_href = '#popup';  $regex = "((https?|ftp)\:\/\/)?"; // scheme $regex .= "(localhost)"; // host or ip $regex .= "(\/([a-z0-9+\$_-]\.?)+)*\/?"; // path  $pattern = "/$regex/";  $newcontent = preg_replace($pattern, $new_href, $link); echo $newcontent;  ?> 

output:

<a href="#popup">client portal</a> 

Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

node.js - How to abort query on demand using Neo4j drivers -