PHP - 如何在某个字符处拼接字符串? [英] PHP - How to splice a string at a certain character?
问题描述
我想创建一个函数,从冒号后的文件中获取每一行.我无法在所述字符处切割字符串.
I want to make a function that grabs each line from a file after the colon. I'm having trouble slicing the string at said character.
所以我想切片:
日期:2017 年 3 月 27 日"到2017 年 3 月 27 日"开始:12:30pm"到12:30pm"......等
"date: march 27, 2017" to "march 27, 2017" "start: 12:30pm" to "12:30pm" ...etc.
注意:我不需要帮助编写实际函数,我只想知道如何拼接第一个冒号处的行
Note: I don't need help writing the actual function, I just want to know how to splice the line at the first colon
推荐答案
对于您的情况,请使用:$string="date: March 27, 2017";
或 $string="开始:12:30pm";
For your case, using: $string="date: march 27, 2017";
or $string="start: 12:30pm";
您可以选择以下任何一种技术:
You can select any one of these techniques:
*注意:如果担心针的存在(colon 或 colon space),那么您应该采用防伪选项之一,否则需要额外的考虑才能在没有针的情况下接住绳子.
*note: If there are concerns about the existence of the needle (colon or colon space) then you should employ one of the options that is false-proof, otherwise additional considerations will be necessary to catch strings without the needle.
Use strpos() & substr() *false-proof:
$string=($pos=strpos($string,": "))?substr($string,$pos+2):$string;
Use strstr() & substr() *false-proof:
$string=($sub=strstr($string,": "))?substr($sub,2):$string;
使用explode() *需要冒号空间em> 存在:
Use explode() *requires colon space to exist:
$string=explode(': ',$string,2)[1];
使用 explode() &end() *不再是单线,而是防伪:
Use explode() & end() *no longer a one-liner, but false-proof:
$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() 和 正则表达式模式 *防伪:
Use preg_replace() with a regex pattern *false-proof:
$string=preg_replace("/(^.*?:\s)/","",$string);
使用 preg_match() 和 正则表达式模式 不是单行的,而是防伪的:
Use preg_match() with a regex pattern not a one-liner, but false-proof:
preg_match("/^.*?:\s(.*)/",$string,$captured);
$string=(sizeof($captured))?end($captured):$string;
使用 str_replace() *不是单行的,但防伪:
Use str_replace() *not a one-liner, but false-proof:
$search=array("date: ","start: ");
$replace="";
$count=1;
$string=str_replace($search,$replace,$string,$count);
这是一个演示,适用于可能想在自己的雪花上运行一些测试的人案例.
Here is a Demo for anyone who might want to run some tests on their own snowflake case.
这篇关于PHP - 如何在某个字符处拼接字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!