2

I need a regex to remove all space before a specific character.

Exemple:

Remove all space before the first " - "

Before:

My Beautiful Video - Hello darling - 19.10.2015 10:00

After:

MyBeautifulVideo - Hello darling - 19.10.2015 10:00
Community
  • 1
  • 1
David Zeller
  • 61
  • 1
  • 6

2 Answers2

1

You may use (*SKIP)(*F) or capturing group.

preg_replace('~ - .*(*SKIP)(*F)| ~', '', $str);

syntax of the above regex control verb must be like,

What_I_want_to_avoid(*SKIP)(*FAIL)|What_I_want_to_match

So - .* part should match all the chars from the first space hyphen space to the last. Now the control verb (*SKIP)(*F) makes the match to fail. Now the regex after the OR operator will do matching only from the remaining string. It won't work if you use .*, .*? in the alternate branch.

source

or

preg_replace('~( - .*)| ~', '\1', $str);

DEMO

DEMO

Community
  • 1
  • 1
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
1
\s*-.*$\K|\s

You can use \K here and replace by empty string.

Demo on regex101

$re = '/\s*-.*$\K|\s/m'; 
$str = "My Beautiful Video - Hello darling - 19.10.2015 10:00"; 
$subst = ""; 

$result = preg_replace($re, $subst, $str);
nhahtdh
  • 55,989
  • 15
  • 126
  • 162
vks
  • 67,027
  • 10
  • 91
  • 124