Replace anchor text with PHP (and regular expressi

2019-07-21 06:33发布

问题:

I have a string that contains a lot of links and I would like to adjust them before they are printed to screen:

I have something like the following:

<a href="http://www.dont_replace_this.com">replace_this</a>

and would like to end up with something like this

<a href="http://www.dont_replace_this.com">replace this</a>

Normally I would just use something like:

echo str_replace("_"," ",$url); 

In in this case I can't do that as the URL contains underscores so it breaks my links, the thought was that I could use regular expression to get around this.

Any ideas?

回答1:

This will cover most cases, but I suggest you review to make sure that nothing unexpected was missed or changed.

 pattern = "/_(?=[^>]*<)/";
 preg_replace($pattern,"",$url);


回答2:

Here's the regex: <a(.+?)>.+?<\/a>.

What I'm doing is preserving the important dynamic stuff within the anchor tag, and and replacing it with the following function:

preg_replace('/<a(.+?)>.+?<\/a>/i',"<a$1>REPLACE</a>",$url);


回答3:

You can use this regular expression

(>(.*)<\s*/) 

along with preg_replace_callback .

EDIT :

$replaced_text = preg_replace_callback('~(>(.*)<\s*/)~g','uscore_replace', $text);  
function uscore_replace($matches){
   return str_replace('_','',$matches[1]); //try this with 1 as index if it fails try 0, I am not entirely sure
}


标签: php regex anchor