1

So here is my code. I have to replace a space with an asterisk and if there are an occurence of two spaces in a row in the string replace it with one dash

<?php
$string = "Keep your    spacing   perfect!";
$search = array(' ','  ');
$search2 = array('*','-');
echo str_replace($search, $search2, $string);
?> 

when i run it it prints out

Keep*your****spacing***perfect!

which is suppose to be

Keep*your--spacing-*perfect!

so what is wrong with my code and how do i fix it? I did some research but could not come to a solution. Any help is appreciated!

3 Answers 3

1

You have just to swap your replaces. Because you replace single space before replacing double spaces.

$string = "Keep your    spacing   perfect!";
$search = array('  ',' '); // swap !
$search2 = array('-','*'); // swap !
echo str_replace($search, $search2, $string);

Outputs:

Keep*your--spacing-*perfect!
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

<?php
$string = "Keep your    spacing   perfect!";
$string1 = preg_replace("/\s\s/", "-", $string);
$string2 = preg_replace("/\s/", '*', $string1);
echo $string2;
?>

The output of this is the following:

Keep*your--spacing-*perfect!

Comments

0

The answer is this line in the PHP manual entry for str_replace:

If search or replace are arrays, their elements are processed first to last.

So just put the order of the array values in the opposite order:

<?php
$string = "Keep your    spacing   perfect!";
$search = array('  ',' ');
$search2 = array('-','*');
echo str_replace($search, $search2, $string);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.