2016-10-24 67 views
0

我有以下的輸出:PHP str_replace函數與偏移

Item 
Length : 130 
Depth : 25 
Total Area (sq cm): 3250 
Wood Finish: Beech 
Etc: etc 

我想刪除的總面積(平方釐米):從字符串後,它和4個位數,目前我正在嘗試使用str_replace函數像這樣:

$tidy_str = str_replace($totalarea, "", $tidy_str); 

這是使用正確的功能,如果是的話我怎麼能包括該文本之後的4個隨機數字?請注意,這不是一個設定的輸出,所以字符串會在這個位置改變位置。

+1

'preg_replace' http://php.net/manual/en/function.preg-replace.php – Scott

回答

0

這將做到這一點。

$exp = '/\(sq cm\): \d+/'; 


echo preg_replace($exp, '', $array); 
0

試試這個:

preg_replace('/(Total Area \(sq cm\):)([0-9\.,]*)/' , '', $tidy_str); 
1

你可以練習在http://www.phpliveregex.com/

<?php 

$str = ' 
Item 
Length : 130 
Depth : 25 
Total Area (sq cm): 3250 
Wood Finish: Beech 
Etc: etc 
'; 

echo preg_replace("/Total Area \(sq cm\): [0-9]*\\n/", "", $str); 
Item 
Length : 130 
Depth : 25 
Wood Finish: Beech 
Etc: etc 
0

PHP正則表達式您正在尋找substr_replace

$strToSearch = "Total Area (sq cm):"; 
$totalAreaIndex = strpos($tidy_str, $strToSearch); 
echo substr_replace($tidy_str, '', $totalAreaIndex, strlen($strToSearch) + 5); // 5 = space plus 4 numbers. 

如果你想刪除的換行符也是如此,你應該檢查它是\ n還是\ r \ n。 \ n添加一個,\ r \ n添加兩個以抵消。 IE瀏覽器。 strlen($strToSearch) + 7