Reputation: 23
I have this input string: '- - Adele Gislan - Web Developer - - - '
and the expected output is this string: Adele Gislan - Web Developer
I use this regular expression
$urli='- - Adele Gislan - Web Developer - - - ';
$urli = preg_replace("/\-[[:space:]]+$/","",$urli);
$urli = preg_replace("/\-+$/","",$urli);
But this remove special character "-" or "- " only one time.
I try this
$urli = rtrim($urli, '-');
$urli = ltrim($urli, '-');
but isnt ideal
Upvotes: 0
Views: 288
Reputation: 74645
If you just want to trim leading and trailing dashes and spaces, there's no need to use regular expressions. You could use one call to trim
:
echo trim($urli, '- ');
The second argument is a list of characters to be removed.
Output:
Adele Gislan - Web Developer
Upvotes: 0
Reputation: 174716
You need to include the space and -
symbol inside a character class,
^[ -]+|[ -]+$
Just replace the matched characters with an empty string.
PHP code would be,
<?php
$mystring = "- - Adele Gislan - Web Developer - - - ";
echo preg_replace('~^[ -]+|[ -]+$~', '', $mystring);
?>
Output:
Adele Gislan - Web Developer
Explanation:
^
Asserts that we are at the start.[ -]+
Matches one or more space or -
characters.|
Logical OR operator which is usually used to combine two regexes.[ -]+
Matches one or more space or -
characters.$
Asserts that we are at the end of the line.Upvotes: 1
Reputation: 10148
I'd be extra-greedy and simply match word bounds:
$str = ' - - Adele Gislan - Web Developer - - -';
$str = preg_replace('/.*?(\b.+\b).*/', '$1', $str);
Upvotes: 0
Reputation: 4897
To get from:
- - Adele Gislan - Web Developer - - -
to
Adele Gislan - Web Developer
use:
[ -]{4,}
php-preg:
'/[ -]{4,}/m'
Alternatively you could use:
(?: *-+ *){2,}
php-preg:
'/(?: *-+ *){2,}/m'
Upvotes: 0