You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP字符串操作求助:指定位置添加内容与动态修改文件名方法

Hey there! Let's tackle your PHP questions one by one, step by step.

1. Fixing Your String Modification Issue

You need to transform localhost/uploads/images/photo.jpg to localhost/upload/images/photo_thumb.jpg—two key changes: replacing uploads with upload, and inserting _thumb between the filename and its extension.

The Cleanest Approach: Use pathinfo()

pathinfo() breaks down the path into manageable parts, so you don't have to manually hunt for positions (which avoids headaches with edge cases like filenames containing dots):

$originalUrl = 'localhost/uploads/images/photo.jpg';
$pathDetails = pathinfo($originalUrl);

// Update the directory part (swap "uploads" for "upload")
$updatedDir = str_replace('uploads', 'upload', $pathDetails['dirname']);
// Build the new filename: original name + "_thumb" + extension
$newFilename = $pathDetails['filename'] . '_thumb.' . $pathDetails['extension'];
// Combine everything into the final URL
$finalUrl = $updatedDir . '/' . $newFilename;

echo $finalUrl; // Outputs: localhost/upload/images/photo_thumb.jpg

If You Want to Use strpos() (or strrpos())

If you prefer working directly with string positions, use strrpos() to find the last dot (this handles filenames with multiple dots like photo.v2.jpg):

$originalUrl = 'localhost/uploads/images/photo.jpg';
// First fix the "uploads" → "upload" part
$tempUrl = str_replace('uploads', 'upload', $originalUrl);
// Find the position of the last dot
$lastDotPos = strrpos($tempUrl, '.');
// Insert "_thumb" before the dot
$finalUrl = substr($tempUrl, 0, $lastDotPos) . '_thumb' . substr($tempUrl, $lastDotPos);

echo $finalUrl; // Same correct output
2. Most Efficient Ways to Insert Content into a String in PHP

The best method depends on your use case:

For Fixed Positions: substr() (or mb_substr() for Multibyte Text)

This is the fastest option for exact positions, since it’s a native low-overhead operation:

$string = 'Hello World';
$insertText = 'Amazing ';
$insertPosition = 6; // Insert after "Hello "

$newString = substr($string, 0, $insertPosition) . $insertText . substr($string, $insertPosition);
// Outputs: Hello Amazing World

For multibyte characters (like Chinese, Arabic), use mb_substr() to avoid garbled text:

$string = '我爱编程';
$insertText = 'PHP ';
$insertPosition = 2; // Insert after "我爱"

$newString = mb_substr($string, 0, $insertPosition) . $insertText . mb_substr($string, $insertPosition);
// Outputs: 我爱PHP 编程

For Structured Strings (Like Paths/URLs): Use Specialized Functions

As shown in your URL example, functions like pathinfo(), dirname(), and basename() are more efficient and readable than manual position hunting. They’re optimized for this kind of work and reduce the chance of bugs.

For Pattern-Based Insertions: preg_replace()

If you need to insert text based on a pattern (e.g., before all numbers), use regex. It’s less performant than substr() but far more flexible:

$string = 'user123';
// Insert an underscore before digits
$newString = preg_replace('/(\d+)/', '_$1', $string);
// Outputs: user_123
3. Example Implementation for get_google_image_url()

Since your function is incomplete, I’ll assume it generates Google Image URLs based on a $type parameter. Here’s a practical example (adjust based on your actual needs):

function get_google_image_url($type, $size = '640x480') {
    // Base URL (adjust if using Google's Custom Search API)
    $baseUrl = 'https://www.google.com/images';
    
    // Map types to image keywords
    $typeKeywords = [
        'nature' => 'sunset mountain landscape',
        'tech' => 'wireless headphones',
        'food' => 'homemade sushi'
    ];
    
    // Fallback to a default keyword if the type isn't recognized
    $keyword = $typeKeywords[$type] ?? 'random creative image';
    
    // Build the final URL with encoded parameters
    return $baseUrl . '?q=' . urlencode($keyword) . '&size=' . urlencode($size);
}

// Usage example
echo get_google_image_url('nature');
// Outputs: https://www.google.com/images?q=sunset+mountain+landscape&size=640x480

If you have specific requirements (like integrating with Google’s official API), share more details and I can refine this further.

内容的提问来源于stack exchange,提问作者Emmanuel agahiu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:20:46