gpt4 book ai didi

php - 在回显之前编辑字符串中的 url?

转载 作者:行者123 更新时间:2023-11-29 06:55:13 24 4
gpt4 key购买 nike

不确定如何完成,但如何在回显来自数据库的结果之前编辑字符串中的 url?

基本上:

来自数据库的字符串:

Hello, I am Terry. I like using <a href="http://www.twitter.com">Twitter</a>, but I prefer using <a href="http://www.facebook.com">Facebook</a>. I like posting blogs on my website at <a href="http://www.mycoolsite.com">My Cool Site</a>, and I enjoying playing sports.

但我想回显:

Hello, I am Terry. I like using <a href="http://www.somepage.com/home?url=http://www.twitter.com">Twitter</a>, but I prefer using <a href="http://www.somepage.com/home?url=http://www.facebook.com">Facebook</a>. I like posting blogs on my website at <a href="http://www.somepage.com/home?url=http://www.mycoolsite.com">My Cool Site</a>, and I enjoying playing sports.

例如:替换 http://www.twitter.com在 href 中带有 http://www.somepage.com/home?url=http://www.twitter.com

最佳答案

这才是你真正要找的,

<?php   /** PHP, JavaScript and HTML/CSS mixed-code sample */

$string = 'Hello, I am Terry. I like using <a href="http://www.twitter.com">Twitter</a>, but I prefer using <a href="http://www.facebook.com">Facebook</a>. I like posting blogs on my website at <a href="http://www.mycoolsite.com">My Cool Site</a>, and I enjoying playing sports.';
$myurl = "http://www.somepage.com/home?url=";

$result = preg_replace('/(<a[^>]*href[\s]*=["|\'])(.*?["|\'])/', "$1$myurl$2", $string);

echo $result;
?>

您可以在 phpfiddle.org 上尝试该代码,它正在运行。如果您需要任何更改,请告诉我。

更新代码:

<?php
$string = 'Hello, I am Terry. I like using <a href="http://www.twitter.com">Twitter</a>, but I prefer using <a href="http://www.facebook.com">Facebook</a>. I like posting blogs on my website at <a href="http://www.mycoolsite.com">My Cool Site</a>, and I enjoying playing sports.';
$myurl = "http://www.somepage.com/home?url=";

preg_match_all('/(<a[^>]*href[\s]*=)["|\'](.*?)["|\']/', $string, $result, PREG_SET_ORDER);

for($i=0;$i<count($result);$i++){
$string = str_replace($result[$i][0], $result[$i][1] .'"'. $myurl . urlencode($result[$i][2]) .'"' ,$string);
}

?>
<!--<textarea><?php echo $string; ?></textarea>-->
<?php echo $string; ?>

关于php - 在回显之前编辑字符串中的 url?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13152706/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com