Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace dashes in to space using php

Tags:

regex

php

can you help me in my problem.

i want to create a function to replace the space into dash then i found a solution for that

this is the sulotion i found:

function slug($phrase, $maxLength=100000000000000)
    {
        $result = strtolower($phrase);

        $result = preg_replace("/[^A-Za-z0-9\s-._\/]/", "", $result);
        $result = trim(preg_replace("/[\s-]+/", " ", $result));
        $result = trim(substr($result, 0, $maxLength));
        $result = preg_replace("/\s/", "-", $result);

        return $result;
    }

my problem is i want to create a vice versa for that replace dash to space

example input:

dash-to-space

example output

dash to space

how can i do that?

like image 962
PPjyran Avatar asked Dec 25 '22 01:12

PPjyran


1 Answers

You can use this lookaround based preg_replace:

$result = preg_replace('/(?<!\s)-(?!\s)/', ' ', $input);

RegEx Demo

This will avoid replacing - by space if it is surrounded by space.

like image 134
anubhava Avatar answered Dec 27 '22 21:12

anubhava