【问题标题】:Cutting a string when it hits a dot [duplicate]当它碰到一个点时切割一个字符串[重复]
【发布时间】:2014-04-27 16:02:07
【问题描述】:

我有一个名为 image_name 的变量。下面的例子

$image_name = "hello.png";

当它看到点时,我想剪断字符串。因为我想添加一个随机整数,所以名称不能重复。例如,目前在我的代码中我有

$image_name = substr($image_name, 0, 10) . time() . rand(0, 9999);

上面的测试字符串会返回类似

hello.png13953322416647

我的目标是让字符串名称等于 hello13953322416647.png - 在所有时间戳和随机数之后显示 .png

那么有谁知道当它碰到字符串中的一个点时如何剪切字符串然后在末尾添加它..?

谢谢大家

【问题讨论】:

  • 你试过substr($image_name, 0, strrpos($image_name, '.')). time().rand(0, 9999).substr($image_name, strrpos($image_name, '.'))吗?

标签: php string substring


【解决方案1】:

我会使用 pathinfo 函数。 http://php.net/manual/en/function.pathinfo.php

$path_detail = pathinfo( $image_name );
$new_image_path = sprintf( "%s%s%s%s", $path_detail['filename'], time(), rand( 0,9999), $path_detail['extension']); 

【讨论】:

  • +1:这是正确的做法。
猜你喜欢
  • 1970-01-01
  • 2014-12-11
  • 1970-01-01
  • 1970-01-01
  • 2018-07-30
  • 1970-01-01
  • 1970-01-01
  • 2017-11-10
  • 1970-01-01
相关资源
最近更新 更多