1

not sure how it can be done, but how can I edit the urls in a string before echoing results from the db?

basically:

the string coming from db:

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.

but I want to echo out:

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.

eg: Replace http://www.twitter.com in href with http://www.somepage.com/home?url=http://www.twitter.com

4

3 回答 3

1
$string="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."

preg_replace('/<a href="([^"]*)" >/','<a href="someurl?url=$1" >',$string)
于 2012-10-31T06:58:23.563 回答
1

This is what you are actually looking for,

<?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;
?>

You can try that code on phpfiddle.org it's working. Let me know if you need anything change in that.

UPDATED CODE:

<?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; ?>
于 2012-10-31T07:07:47.230 回答
0

Quick and dirty way to get it done,

$new_string = str_replace('href="', 'href="http://www.somepage.com/home?url=', $old_string);
于 2012-10-31T06:57:30.530 回答