Replace anchor text with PHP (and regular expression)

萝らか妹 提交于 2019-12-24 03:26:21

问题


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
}


来源:https://stackoverflow.com/questions/7532558/replace-anchor-text-with-php-and-regular-expression

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!