views:

2339

answers:

6

Hiya,

Despite using PHP for years, I've never really learnt how to use expressions to truncate strings properly... which is now biting me in the backside!

Can anyone provide me with some help truncating this? I need to chop out the text portion from the url, turning

<a href="link.html">text</a>

into

<a href="link.html"></a>

Any help appreciated ;)

H

+3  A: 

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.

Pascal MARTIN
+4  A: 
$str = preg_replace('#(<a.*?>).*?(</a>)#', '$1$2', $str)
Amber
+1  A: 

You could use substring in combination with stringpos, eventhough this is not a very nice approach.

Check:

PHP-Stringfunctions

Another way would be to write a regular expression to match your criteria. But in order to get your problem solved quickly the string functions will do...

EDIT: I underestimated the audience. ;) Go ahead with the regexes... ^^

KB22
+4  A: 

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;
?>
karim79
A: 

strip_tags function also helps with this.

http://us.php.net/strip%5Ftags

MANCHUCK
A: 

I have a smilar problem.

I need to convert:

<a href="link.html">text</a>

into

text

I mean i want to remove some links my DB. What should i do?

Mehmet