2014-01-05 29 views
0

我怎麼能做到這一點?PHP如果字符串包含'+',請將其更改爲'測試'?

我對str操作員很熟悉,但我很不確定我怎麼能夠做到這一點。

邏輯測試:

If (string.contains == '+') { 
string.change("test"); 
} 

基本上它需要什麼:

it'll be used for a string that contains more then just a + e.g. hello+hello will change into -> hellotesthello 
+0

您應該提供一些例子,如'hello + hello'>'hellotesthello' –

回答

2
if(strpos($string, '+') !== false){ 
    $string = 'test'; 
} 

如果你想改變+test你會使用

$string = str_replace('+', 'test', $string); 
+0

對於較短的語法:'if(strstr($ string,'+'))' – Sam

+0

'Note: 如果您只想確定是否在乾草堆內發生一個特殊的針,使用更快,更少的內存密集功能strpos()代替。' – Jessica

+0

感謝@Jessica,每天都在學習一些東西。 – Sam

0
$string = preg_replace('/\+/','test',$string); 
+1

正則表達式對於如此簡單的事情來說是不必要的資源使用。 – Sam

+0

其實我並不知道strpos和str_replace顯着更快。 –

+0

沒問題..我不知道'strpos'比'strstr'快。 – Sam

相關問題