2015-07-20 28 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

像魅力一样工作。很好的答案,尤其对你的评论解释有帮助。谢谢! –