PHP - 如何将字符串拼接在某个字符上



我想创建一个函数,从冒号后面的文件中提取每一行。我在所述字符上切片字符串时遇到问题。

所以我想切片这个:

"日期:2017 年 3 月 27 日"至"2017 年 3 月 27 日"开始:中午 12:30"到"中午 12:30"......等。

注意:我不需要帮助编写实际函数,我只想知道如何拼接第一个冒号处的行

对于您的情况,请使用: $string = "date: march 27, 2017";$string = "start: 12:30pm";

您可以选择以下任一技术:

*注意:如果担心针的存在(结肠或结肠空间(,那么您应该使用防伪的选项之一,否则需要额外的考虑来捕捉没有针头的绳子。

使用 strpos(( & substr(( *false-proof:

$string = ($pos = strpos($string, ": ")) ? substr($string, $pos + 2) : $string;

使用 strstr(( & substr(( *false-proof:

$string = ($sub = strstr($string, ": ")) ? substr($sub, 2) : $string;

使用 explode(( *需要冒号空格才能存在:

$string = explode(': ', $string, 2)[1];

使用 explode(( & end(( *不再是单行,而是防伪:

$array = explode(': ', $string, 2);
$string = end($array);
// nesting explode() inside end() will yield the following notice:
// NOTICE Only variables should be passed by reference

将 preg_replace(( 与正则表达式模式一起使用 *防伪:

$string = preg_replace("/^.*?:s/", "", $string);

将 preg_match(( 与正则表达式模式一起使用,而不是单行,而是防伪:

$string = preg_match("/^.*?:sK.*/", $string, $m) ? $m[0]: $string;

这是一个演示,适合任何可能想在自己的雪花案例上运行一些测试的人。

正如@chris85所建议的,使用 strpossubstr 的解决方案:

$date = "date: march 27, 2017";
$yourString = $date;
//get the position of `:`
if(strpos($date, ":")!==false) {
    //get substring    
    $yourString = substr($date, strpos($date, ":") + 1);    
}
echo $yourString;

编辑

根据@mickmackusa评论,上述答案在提取的文本之前可能有尾随空格,您可以使用:

$yourString = ltrim($yourString)

使用 strstr - http://php.net/manual/en/function.strstr.php

应该喜欢接近的东西

$str = 'date: march 27, 2017';
$str = strstr($str, ':');
$str = trim(substr($str, 1));
var_dump($str);
string(14) "march 27, 2017"

尚未对其进行测试,但根据文档,它应该可以解决问题

这是一个简单的解决方案:

var_dump(explode(':', "date: march 27, 2017", 2));

这将输出以下内容:

array(2) {
  [0]=>
  string(4) "date"
  [1]=>
  string(15) " march 27, 2017"
}

然后,您将值放在 [1] 索引中,开始值位于 [0] 索引中。这将允许您在需要时执行其他逻辑。

然后,您可以对该值调用 trim(( 以删除任何空格。

你可以在: http://php.net/manual/en/function.explode.php explode

然后将阵列拼接 http://php.net/array_splice

并用implode http://php.net/manual/en/function.implode.php 恢复字符串

另请参阅:如何拼接数组以在特定位置插入数组?

$x=explode(':',$string);
array_splice($x, 1, 0, ['text_Added']);
$string = implode($x);

编辑:

如果你只想从字符串中删除日期:,你可以用第二个参数作为filter.http://php.net/manual/en/function.trim修剪它.php

echo trim('date: march 27, 2017" to "march 27, 2017" "start: 12:30pm" to "12:30pm','date:');
//march 27, 2017" to "march 27, 2017" "start: 12:30pm" to "12:30pm

甚至只是str_replace它。 对于第 4 个参数,1 在 1rst 替换后停止 http://php.net/manual/en/function.str-replace.php

最新更新