2015-07-20 29 views
-1

我需要在php中替換兩個字符之間的一部分字符串,最後一個連字符和最後一個點。有任何想法嗎?替換連字符和點之間的字符串的一部分在php

$string = 'http://example.com/wp-content/uploads/2015/07/2b146fdab6c33eb5ca12efe61424427b-1000x750.jpg' 

數字可以變化,1000x750只是一個例子。

$newstring = 'http://example.com/wp-content/uploads/2015/07/2b146fdab6c33eb5ca12efe61424427b-600x400.jpg' 

謝謝!

+0

你有沒有嘗試過的東西或者做了一些研究? – Rizier123

+0

我確實設法在字符串上添加新字符串,而不用像連字符 '$ first_img =''; ob_start(); ob_end_clean(); $ output = preg_match_all('/ /i',$ post-> post_content,$ matches); $ first_img = $ matches [1] [0]; $ first_img = substr($ first_img,0,-4)。' - 600x450'。 substr($ first_img,-4);' –

+1

然後在你的問題中顯示你的努力以及你被困在哪裏。 – Rizier123

回答

1

您可能會發現這個腳本有所幫助:

// The string you want to replace between the two characters 
$replacewith = "600x400"; 

// The example string you provided 
$string = $newstring = 'http://example.com/wp-content/uploads/2015/07/2b146fdab6c33eb5ca12efe61424427b-1000x750.jpg'; 

// Determine the start/end position of the last hyphen and period characters 
$start = strrpos($string, "-"); 
$end = strrpos($string, "."); 

// If both the hyphen and character are found, then do the replacement 
if ($start && $end) { 

    $newstring = substr($string, 0, $start+1) . $replacewith . substr($string, $end); 

} 

echo $newstring; 

// Outputs http://example.com/wp-content/uploads/2015/07/2b146fdab6c33eb5ca12efe61424427b-600x400.jpg 
+0

像魅力一樣工作。很好的答案,尤其對你的評論解釋有幫助。謝謝! –