tags:

views:

86

answers:

3

i want to delete the following type of expressions from my script.

<a any text here>nothing or space here</a>

i can do it by three functions, but i think there is a way shorter. could you help me? thanks in advance

A: 

Taken from http://www.regular-expressions.info/php.html:

mixed preg_replace (mixed pattern, mixed replacement, mixed subject [, int limit]) returns a string with all matches of the regex pattern in the subject string replaced with the replacement string.

At most limit replacements are made. One key difference is that all parameters, except limit, can be arrays instead of strings.

In that case, preg_replace does its job multiple times, iterating over the elements in the arrays simultaneously. You can also use strings for some parameters, and arrays for others. Then the function will iterate over the arrays, and use the same strings for each iteration. Using an array of the pattern and replacement, allows you to perform a sequence of search and replace operations on a single subject string. Using an array for the subject string, allows you to perform the same search and replace operation on many subject strings.

phimuemue
+2  A: 

will preg_replace('/<a(.*?)>\s*<\/a>/', '', $str) work ?

EDIT: Alan Moore is right, thx

nc3b
preg_replace('/<a(.*)>.*<\/a>/', '', $str) will. http://rubular.com/r/uFatSqs2Vj
Gazler
+1, except "nothing or space here" implies `\s*` to me, not `\s+`.
Alan Moore
@Gazler: if there are two `<a>` elements on one line, your regex will match both at once, plus whatever's between them.
Alan Moore
A: 
$text = '<a any text here>nothing or space here</a>';
$rep = '';
$pat = '|<a[^>]*>\S*</a>|';
echo preg_replace($pat,$rep,$text);

EDIT: the wrong one

$text = '<a any text here>nothing or space here</a>';
$rep = '<a>\1</a>';
$pat = '|<a[^>]*>([^<]*)</a>|';
echo preg_replace($pat,$rep,$text);
Cesar
I think the OP wants to remove the whole string, not just the "any text here" part" (the red coloring is just SO's syntax highlighter being a little too enthusiastic).
Alan Moore
ops, what a noob... I'm sorry it's my 4th day and I'm still stepping into pitfalls, trying to do my best.
Cesar