在php中替换连字符和点之间的字符串的一部分

时间:2015-07-20 00:25:38

标签: php preg-replace

我需要在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'

谢谢!

1 个答案:

答案 0 :(得分: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