5

SO中有类似的 问题,但我找不到任何与此完全相同的问题。我需要删除直到(包括)特定分隔符的所有内容。例如,给定字符串File:MyFile.jpg,我需要删除直到 的所有内容:,这样我就只剩下 了MyFile.jpg。提前致谢!

4

7 回答 7

9

使用这个 preg_replace 调用:

$str = 'File:MyFile.jpg';
$repl = preg_replace('/^[^:]*:/', '', $str); // MyFile.jpg

或者避免使用正则表达式并像这样使用explode:

$repl = explode(':', $str)[1]; // MyFile.jpg

编辑:使用这种方式来避免正则表达式(如果字符串中可以有多个 : ):

$arr = explode(':', 'File:MyFile.jpg:foo:bar');
unset($arr[0]);
$repl = implode(':', $arr); // MyFile.jpg:foo:bar
于 2013-04-19T12:36:55.743 回答
4

编辑:这个工作正常。

$str = "File:MyFile.jpg";
$str = substr( $str, ( $pos = strpos( $str, ':' ) ) === false ? 0 : $pos + 1 );
于 2013-04-19T12:37:04.597 回答
3

更短的代码:

要在字符第一次出现之前返回所有内容,请使用. 例子:strtok

  • strtok(16#/en/go, '#')将返回16

要在第一次出现字符返回所有内容,请使用. 例子:strstr

  • strstr(16#/en/go, '#')将返回#/en/go(包括搜索字符“#”)
  • substr(strstr(16#/en/go, '#'), 1)将返回/en/go

要在最后一次出现字符返回所有内容,请使用. 例子:strrchr

  • strrchr(16#/en/go, '/')将返回/go(包括搜索字符“/”)
  • substr(strrchr(16#/en/go/, '/'), 1)将返回go
于 2017-02-19T13:15:10.923 回答
1

你可以explode这样做:链接

就像是:

$string = "File:MyFile.jpg";
list($protocol,$content) = explode(":", $string);
echo $content;
于 2013-04-19T12:37:27.187 回答
1
    $str = "File:MyFile.jpg";

    $position = strpos($str, ':');//get position of ':'

    $filename= substr($str, $position+1);//get substring after this position
于 2013-04-19T14:28:26.207 回答
0

两种简单的方法:

$filename = str_replace('File:', '', 'File:MyFile.jpg');

或者

$filename = explode(':', 'File:MyFile.jpg');
$filename = $filename[1];
于 2013-04-19T12:37:29.747 回答
0

示例字符串:

$string = 'value:90|custom:hey I am custom message|subtitute:array';

将字符串转换为数组

$var = explode('|', $string);

检查结果:

Array(
[0] => value:90
[1] => custom:hey I am custom message
[2] => subtitute:array)

声明一个数组变量

$pipe = array();

循环遍历字符串数组 $var

foreach( $var as $key => $value ) {
  // get position of colon
  $position = strrpos( $value, ':' );
  // get the key
  $key = substr( $value, 0, $position );
  //get the value
  $value = substr( $value, $position + 1 );
  $pipe[$key] = $value; }

最后结果:

Array(
[value] => 90
[custom] => hey I am custom message
[subtitute] => array)
于 2015-03-30T15:24:40.210 回答