Reputation: 873
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
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
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
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
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