0

I need help with some regex operation in php.

I have string e.g.

$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

Sagar V
  • 12,158
  • 7
  • 41
  • 68
  • *"I cannot use simple html parser and other libraries"* ... not even the in-built `DOMDocument` ? You're likely to have a bad time with RegExp and HTML... – CD001 Jun 21 '17 at 15:08
  • `I cannot use simple html parser and other libraries`, why not? You can use `preg_replace`? Have you tried anything with that if you can use it? – chris85 Jun 21 '17 at 15:08
  • I`ll try to use DOMDocument if its build in php. I have missed it. I cannot use external libraries. – Jerzy Jerzynka Jun 21 '17 at 16:34
  • Avoid at all cost from using regex to parse HTML. – Omri Luzon Jun 21 '17 at 19:28

1 Answers1

0

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
    ?>  
cody collicott
  • 261
  • 2
  • 6
  • Thank You, problem is that i really need anchor text (click here) and second problem is that string can contain more than one link. Your code replace all links to first occured href. – Jerzy Jerzynka Jun 21 '17 at 16:30