Abaij
Abaij

Reputation: 873

How to insert a white space into a string in php?

I want to separate a string with a whitespaces based on the pattern I want. In every two words and sometimes three. For example:

$string = 'marketplace';

become

$string = 'mark et pl ace';

I know that preg_replace can do this but I don't know the pattern. Can anybody tell me how to do it? Thanks

Upvotes: 1

Views: 4374

Answers (5)

Shameel Kadannamanna
Shameel Kadannamanna

Reputation: 386

Just use

implode(" ",str_split($string, 2))

Here the important code is

<?php
$string = "market";
echo implode(" ",str_split($string, 2));
?>

str_split converts the $string to an array which contents packs of 2 characters.

then implode will join the arrays with spaces b/w all array values.

Upvotes: 1

C4d
C4d

Reputation: 3282

Use this function. Just decide in which steps the spaces should be placed.

function split_by_position($string, $position){
    $splitted = str_split($string, $position);

    foreach($splitted as $part){
        $result .= $part.' ';
    }
    echo $result;
}

$string = 'market';
echo split_by_position($string, 2);

billyonecan's solution really looks better and for sure shorter. I suggest you to use his one. ^^

Upvotes: 0

l&#39;L&#39;l
l&#39;L&#39;l

Reputation: 47169

This pattern should work with preg_replace:

$result = preg_replace("/(\\w{2})/uim", "$1 ", $string);

example:

http://regex101.com/r/hZ0xA1/1

Upvotes: 1

Yorick
Yorick

Reputation: 793

If you want to use preg_replace...., however @billyonecan's str_split is probably a better way.

preg_replace('/(..)/','$1 ', $string);

Upvotes: 5

user1299518
user1299518

Reputation:

this?

$string = 'market';
echo implode(" ",str_split($string,2));

Upvotes: 4

Related Questions