Shreamy
Shreamy

Reputation: 361

How to replace a letter in a sea of recurring letter with php?

$aEnd = "123/123/432/Omeagle";

$aEnd = str_replace("/", "-", $aEnd); // Output: "123-123-432-Omeagle"
$finda = strpos($aEnd, "-");
$countHypen = 0;
$wordLength = 0;
foreach($aEnd as $word){
    $wordLength += 1;
    if($word == "-"){
        $countHypen +=1;
        if($countHypen == $finda){
            break;
        }       
    }
    $aEnd = substr_replace($aEnd," ",$wordLength, 1);    
}

Problem

As you can see from the code above, I am trying to replace the fourth occurrence of the word but the way I did it is super duper inefficient as I have to run this portion quite a lot of times plus the length of the $aEnd is always changing.

Question

Is there any better way? Thanks.

Expecting Output

From: 123/123/432/Omeagle

To: 123-123-432 Omeagle

Upvotes: 0

Views: 53

Answers (2)

Nick
Nick

Reputation: 147166

You can do all the replacements in one call to preg_replace, replacing / that are followed by another / (/(?=.*/)) with -, and a / not followed by / (/(?=[^/]*$)) with a space:

$aEnd = "123/123/432/Omeagle";
$aEnd = preg_replace(array('#/(?=.*/)#', '#/(?=[^/]*$)#'), array('-', ' '), $aEnd);
echo $aEnd;

Output:

123-123-432 Omeagle

Demo on 3v4l.org

Upvotes: 3

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521194

preg_replace should work here, using the following pattern:

\/(?=.*\/)

This will target any path separator which is not the final one, and then we replace it with dash. After this, we make a single call to str_replace to replace the final remaining path separator with a space.

$aEnd = "123/123/432/Omeagle";
$output = preg_replace("/\/(?=.*\/)/", "-", $aEnd);
$output = str_replace("/", " ", $output);
echo $output;

This prints:

123-123-432 Omeagle

Upvotes: 3

Related Questions