HOw to replace <a href="#" >sometext+url </a> with user defined string using preg_replace?
how can i replace
<a href="#" >sometext+url </a> with url by using preg_replace
i used this function
function parse_url($url) {
$url = preg_replace("#<a\s*[^>]*href=\"#i", "<url>", $url,-1);
$url = preg_replace("<\a>", "开发者_开发百科<url>", $url,-1);
return $url;
}
<?php
function replaceAnchorsWithText($data) {
/**
* Had to modify $regex so it could post to the site... so I broke it into 6 parts.
*/
$regex = '/(<a\s*'; // Start of anchor tag
$regex .= '(.*?)\s*'; // Any attributes or spaces that may or may not exist
$regex .= 'href=[\'"]+?\s*(?P<link>\S+)\s*[\'"]+?'; // Grab the link
$regex .= '\s*(.*?)\s*>\s*'; // Any attributes or spaces that may or may not exist before closing tag
$regex .= '(?P<name>\S+)'; // Grab the name
$regex .= '\s*<\/a>)/i'; // Any number of spaces between the closing anchor tag (case insensitive)
if (is_array($data)) {
// This is what will replace the link (modify to you liking)
$data = "{$data['name']}({$data['link']})";
}
return preg_replace_callback($regex, 'replaceAnchorsWithText', $data);
}
$input = 'Test 1: <a href="http: //php.net1">PHP.NET1</a>.<br />';
$input .= 'Test 2: <A name="test" HREF=\'HTTP: //PHP.NET2\' target="_blank">PHP.NET2</A>.<BR />';
$input .= 'Test 3: <a hRef=http: //php.net3>php.net3</a><br />';
$input .= 'This last line had nothing to do with any of this';
echo replaceAnchorsWithText($input).'<hr/>';
?>
This function will output:
Test 1: PHP.NET1(http: //php.net1).
Test 2: PHP.NET2(HTTP: //PHP.NET2).
Test 3: php.net3 (is still an anchor)
This last line had nothing to do with any of this
This code is from the php docs itself
<?php
function subanchor($url) {
return preg_replace("#<a\s*[^>]*href=\"(.*)\".*>(.*)</a>#i", "<url>\\1+\\2</url>", $url);
}
echo subanchor($argv[1]);
?>
$ php subacnchor.php '<a href="http://hello.com/">trololol</a>'
<url>http://hello.com/+trololol</url>
精彩评论