0

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

1
  • 1
    Your rtrim/ltrim attempt was on the right track. But you want to remove spaces and dashes in unison; so trim($str, "- ") for both. Commented Aug 24, 2014 at 14:47

4 Answers 4

1

You need to include the space and - symbol inside a character class,

^[ -]+|[ -]+$

Just replace the matched characters with an empty string.

DEMO

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.
Sign up to request clarification or add additional context in comments.

Comments

0

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'

Comments

0

I'd be extra-greedy and simply match word bounds:

$str = ' - - Adele Gislan - Web Developer - - -';
$str = preg_replace('/.*?(\b.+\b).*/', '$1', $str);

» fiddle
» regex explanation

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.