Reputation: 41080
$string = 'onetwothreefourfive';
How can I turn this into
$string = ' three ';
When my input is three
?
Upvotes: 1
Views: 512
Reputation: 51970
No need to use crude string manipulation, regex to the rescue!
$string = preg_replace('/(three\K)?./s', ' ', $string);
For details on what is used, if anything is unclear, check out the PCRE Pattern Syntax chapter of the PHP manual.
Upvotes: 2
Reputation: 191819
No need to use expensive and/or complicated regex:
function replace_space($str, $keep, $hold) {
$str = explode($keep, $str);
foreach ($str as &$piece) {
$piece = str_repeat($hold, strlen($piece));
}
return implode($keep, $str);
}
echo replace_space('onetwothreefourfivethreefour', 'three', ' ');
Tested and works with multiple needles in the haystack.
Upvotes: 1
Reputation: 360872
$first_chunk = str_repeat(' ', strpos($string, 'three'));
$last_chunk = str_repeat(' ', strlen($string) - strpos($string, 'three') - strlen($string));
$string = $first_chunk . 'three' . $last_chunk;
not tested, doesn't handle multiple needles in the haystack, YMMV, yada yada yada.
Upvotes: 1