Peter
Peter

Reputation: 21

Regex to replace character either before or after but not both

I am trying to remove a span from a string and one of the dashes before or after like so:

1-2-3-<span>4</span>-5-6   => 1-2-3-5-6

However, the span can be at any position of this string:

<span>1</span>-2-3-4-5-6   => 2-3-4-5-6

1-2-3-4-5-<span>6</span>   => 1-2-3-4-5

So what I need is a regular expression to remove the whole span including one of the dashes (but not both) to maintain the correct syntax of the string (dash separated numbers).

This pattern works, but there must be an easier, nicer way:

'#-<span>[^>]+>|<span>[^>]+>-#'

I appreciate any hints! Pete

Upvotes: 2

Views: 92

Answers (3)

George Ant
George Ant

Reputation: 371

Try this :

#-<[^-]+>|<[^-]+>-#.

It's still working and it's a little smaller!

Upvotes: 1

abhinsit
abhinsit

Reputation: 3272

Check this DEMO:

http://codepad.org/0qsK3jmH

Use any set of input string you mentioned in your question and desired answer would be there on screen.

This will cover all set of cases where a span with number can be in between , at start , or at the end.

PHP code:

<?php
$input = "<span>4</span>-1-2-3-5-6";
 $processed1 = preg_replace("/<span>(\d+)<\/span>/", '',$input );
$processed2 = preg_replace("/--/", '-',$processed1);
$processed3 = preg_replace("/^-/", '',$processed2);
$output = preg_replace("/-$/", '',$processed3);
echo $output;



?>

Upvotes: 0

prava
prava

Reputation: 3986

If you want the output like this - 1-2-3-4-5-6, then you can use strip_tags method:

echo strip_tags('<span>1</span>-2-3-4-5-6');
echo strip_tags('1-2-3-<span>4</span>-5-6');
echo strip_tags('1-2-3-4-5-<span>6</span>');

Upvotes: 0

Related Questions