【问题标题】:How to remove a substring from a string using PHP?如何使用 PHP 从字符串中删除子字符串?
【发布时间】:2012-05-27 02:35:59
【问题描述】:

给定以下字符串

http://thedude.com/05/simons-cat-and-frog-100x100.jpg

我想使用 substrtrim(或任何您认为更合适的方式)返回此内容

http://thedude.com/05/simons-cat-and-frog.jpg

即删除-100x100。我需要的所有图像都将在文件名的末尾,紧接在扩展名之前。

在 SO re Ruby 和 Python 上似乎有对此的回应,但不是 PHP/特定于我的需求。

How to remove the left part of a string?

Remove n characters from a start of a string

Remove substring from the string

有什么建议吗?

【问题讨论】:

  • 您打算硬编码子字符串的值吗?还是要匹配任何 -WIDTHxHEIGHT.ext 形式的子字符串?
  • 您介意链接到您找到的 Ruby 和 Python 版本吗?那里使用的技术可能是相关的。
  • @minitech - 在 OP 中添加了一些链接

标签: php string


【解决方案1】:

如果你想匹配任何宽度/高度值:

  $path = "http://thedude.com/05/simons-cat-and-frog-100x100.jpg";

  // http://thedude.com/05/simons-cat-and-frog.jpg
  echo preg_replace( "/-\d+x\d+/", "", $path );

演示:http://codepad.org/cnKum1kd

使用的模式非常基本:

/ 表示模式的开始
- 字面 - 字符
\d+ 一个数字,1 次或多次
x 字面量 x 字符
\d+ 一个数字,1 次或多次
/ 表示模式的结束

【讨论】:

  • 说到底,这可能是万能的解决方案,以防这些缩略图最终改变大小
【解决方案2】:
$url = "http://thedude.com/05/simons-cat-and-frog-100x100.jpg";
$new_url = str_replace("-100x100","",$url);

【讨论】:

    【解决方案3】:
    $url = str_replace("-100x100.jpg", '.jpg', $url);
    

    使用-100x100.jpg 进行防弹解决方案。

    【讨论】:

    • 但是他需要保留扩展名,所以添加'.jpg'作为替换值
    【解决方案4】:

    如果-100x100 是您尝试从所有字符串中删除的唯一字符,为什么不使用str_replace

    $url = "http://thedude.com/05/simons-cat-and-frog-100x100.jpg";
    str_replace("-100x100", "", $url);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-08
      • 1970-01-01
      • 2011-10-15
      • 2012-04-09
      • 1970-01-01
      • 2015-12-02
      相关资源
      最近更新 更多