How to remove text between tags in php?

What about something like this, considering you might want to re-use it with other hrefs :

$str = '<a href="link.html">text</a>';
$result = preg_replace('#(<a[^>]*>).*?(</a>)#', '$1$2', $str);
var_dump($result);

Which will get you :

string '<a href="link.html"></a>' (length=24)

(I'm considering you made a typo in the OP ? )


If you don't need to match any other href, you could use something like :

$str = '<a href="link.html">text</a>';
$result = preg_replace('#(<a href="link.html">).*?(</a>)#', '$1$2', $str);
var_dump($result);

Which will also get you :

string '<a href="link.html"></a>' (length=24)


As a sidenote : for more complex HTML, don't try to use regular expressions : they work fine for this kind of simple situation, but for a real-life HTML portion, they don't really help, in general : HTML is not quite "regular" "enough" to be parsed by regexes.


Using SimpleHTMLDom:

<?php
// example of how to modify anchor innerText
include('simple_html_dom.php');

// get DOM from URL or file
$html = file_get_html('http://www.example.com/');

//set innerText to null for each anchor
foreach($html->find('a') as $e) {
    $e->innerText = null;
}

// dump contents
echo $html;
?>

$str = preg_replace('#(<a.*?>).*?(</a>)#', '$1$2', $str)

Tags:

Php

String

Regex