简体   繁体   中英

PHP preg_replace link to get href and anchor text and concatenate it

I need help with some regex operation in php.

I have string eg

$string = 'This article is about something. If You want more  
<a href='http://www.google.com'>click here</a>. If not just close

I want to get result like this:

$string = 'This article is about something. If You want more click here -
http://google.com. If not just close

How can I do it in php? I cannot use simple html parser and other libraries

Help please, I have no idea how to achieve this

Couldn't really find a way to do this all in one step, but this should work :

<?php
$link = "This article is about something. If You want more <a href='http://www.google.com'>click here</a>. If not just close"; 
preg_match_all('/<a[^>]+href=([\'"])(.+?)\1[^>]*>/i', $link, $result); // Grab the href
$link = preg_replace("/<a href=.*?>(.*?)<\/a>/",$result[2][0],$link); // remove a tag and replace with href value
echo $link;
// output: This article is about something. If You want more http://www.google.com. If not just close
    ?>  

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