M
M
Maxim Maximov2019-11-11 09:19:28
css
Maxim Maximov, 2019-11-11 09:19:28

How to write a regular expression to replace (space hyphen space "-") with hyphen "-"?

$text = ' Длинный    объемный текст с  ----- --- лишние пробелами -- африка ';
$text1 = preg_replace('|[\s]+|s', ' ', $text);
$text2 = preg_replace('|-[\s]+|s', '-', $text1);
$text3 = preg_replace('|[\s]-+|s', '-', $text2);
echo $text3; // Длинный объемный текст с-лишние пробелами-африка

How to correctly compose a 1-but regular expression to get the text from the $text variable as in the $text3 variable?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladislav Lyskov, 2018-10-18
@Vlatqa

overflow-x:hidden

A
Aricus, 2019-11-11
@Aricus

Haven't tested it, but it looks like it should work. Do not know where you got | as limiters. In every language I know, regex delimiters are / . Also it is not necessary to produce variables beyond necessity.

$text = preg_replace('/[\s]+/s', ' ', $text);
$text = preg_replace('/[\s\-]*-[\s\-]*/s', '-', $text);
echo $text ;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question