2011-08-23 42 views

回答

2

無需使用原始字符串操作,正則表達式來拯救

$string = preg_replace('/(three\K)?./s', ' ', $string); 

有關使用什麼,如果有不清楚的地方,請查看PHP手冊的PCRE Pattern Syntax章細節。

+0

'\ K'是什麼? – powtac

+0

@powtac參見http://php.net/regexp.reference.escape - 它在這裏用來阻止'three'作爲匹配的一部分,所以它不會被替換。 – salathe

+0

'\ K'只在PHP 5.2.4之後有效 –

1

無需使用昂貴的和/或複雜的正則表達式:

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', ' '); 

測試,與在草堆多針的工作原理。

1
$first_chunk = str_repeat(' ', strpos($string, 'three')); 
$last_chunk = str_repeat(' ', strlen($string) - strpos($string, 'three') - strlen($string)); 

$string = $first_chunk . 'three' . $last_chunk; 

未測試,不處理在乾草堆,YMMV,yada yada yada多針。

+0

看起來不錯,忘了'strpos',但仍然鎖定一個整齊的線索; – powtac

相關問題