简体   繁体   中英

Change href in div to normal text

I have one problem. On my website, I have <div id="alpha_bravo"> , with links inside. It looks like this:

<div id="alpha_bravo">
  <p>text text text <a href="...">link</a></p>
</div>

I want change every <a href...> to funny text like suprise , as an example.

How can I do it?

Since you tagged the question with PHP and from the comments below the question it seems that you may want to use server-side functionality, I'm going to give an example using PHP.

One way is to replace only links. You are looking for preg_replace() function that will replace all substrings in the string based on a regex pattern.

$input = "<div id='alpha_bravo'><p>text text text <a href='...'>link</a> and <a href='...'>another link</a></p></div>";
$output = preg_replace("/<a (.*?)>(.*?)<\/a>/i", "surprise", $input);

You can also just remove all HTML tags in the string using strip_tags() function.

$input = "<div id='alpha_bravo'><p>text text text <a href='...'>link</a> and <a href='...'>another link</a></p></div>";
$output = strip_tags($input);

Given that this is coming from a database, first word of advice is that you filter your input before saving it in database.

Secondly, if you don't want those links to render and replace them with some other value then use PHP's function preg_replace() as already mentioned by PetrHejda..

PHP docs: http://php.net/manual/en/function.preg-replace.php

Your <a ...>...</a> pattern may differ if users insert styling and classes. Try using this pattern as your solution: preg_replace("/<a(.+?)href=\\"(.+?)\\"/", "<a$1href=\\"your_value_here\\"", $yourStringHere);

You may use g or i flags. Start here with regular expressions: http://www.regular-expressions.info/ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM