【问题标题】:PHP add multiple strings within a string at multiple positionsPHP在一个字符串中的多个位置添加多个字符串
【发布时间】:2017-07-24 01:41:39
【问题描述】:

虽然这很有效,但正在寻找一种让它变得更干净一点/很多的方法,并在此过程中学习!!! 我将 /thumbs 添加到目录和文件字符串,并将 _thumb 添加到同一字符串的文件名末尾。

从此... Gallery/Test/Image/image.jpg

到这个... Gallery/Test/Image/thumbs/image_thumb.jpg

但是路径的长度可以根据目录结构而改变,但是 /thumbs 总是最后一个目录,_thumb 总是在“.”之前

    $thumb_dir = substr($file, 0, strrpos($file, '/')) . '/thumbs' . substr($file, strrpos($file, '/'));

    $thumbnail = substr($thumb_dir, 0, strrpos($thumb_dir, '.')) . '_thumb' . substr($thumb_dir, strrpos($thumb_dir, '.'));

谢谢

【问题讨论】:

  • 您也可以使用正则表达式:3v4l.org/AjNgC 我不会将其作为答案发布,因为接受的答案绝对是更好的解决方案。但我认为这是一种有趣的方法。

标签: php string substr strpos


【解决方案1】:

pathinfo 如果您的 PHP 版本 > 5.2.0+ 可能会对您有所帮助

$path_parts = pathinfo('Gallery/Test/Image/image.jpg');
echo $path_parts['dirname'].'/thumbs/'.$path_parts['filename'].'_thumb.'.$path_parts['extension'];

代码小解释

$path_parts['dirname'] 将获取在本例中给出的路径的完整目录路径,即Gallery/Test/Image。然后我们在字符串中添加了一个名为'/thumbs/' 的目录。接下来我们应该使用$path_parts['filename'] 获取文件的名称,这将获取image 而不是image.jpg,并且我们在其中添加了'_thumb.'。后来我们加上扩展名。

【讨论】:

  • 我在 5.31,所以我会试一试,非常感谢!
  • 嘿 Mohit,效果很好,谢谢!另外感谢您的解释,我还阅读了功能文档!非常感谢您的帮助!
  • 嘿@Simon。感谢您的客气话。乐意效劳。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-20
  • 2022-01-04
  • 1970-01-01
  • 2018-02-19
  • 1970-01-01
  • 2014-07-17
相关资源
最近更新 更多