我有以下字符串:
$thetextstring = "jjfnj 948"
最后我想要:
echo $thetextstring; // should print jjf-nj948
所以基本上我想做的是删除字符串中的空格,然后用
-
将前 3 个字母与字符串的其余部分分开。
到目前为止我已经
$string = trim(preg_replace('/s+/', ' ', $thetextstring));
$result = explode(" ", $thetextstring);
$newstring = implode('', $result);
print_r($newstring);
我已经能够连接单词,但如何在前 3 个字母后添加分隔符?
使用带有
preg_replace
函数的正则表达式,这将是一行:
^.{3}\K([^\s]*) *
细分:
^ # Assert start of string
.{3} # Match 3 characters
\K # Reset match
([^\s]*) * # Capture everything up to space character(s) then try to match them
PHP代码:
echo preg_replace('~^.{3}\K([^\s]*) *~', '-$1', 'jjfnj 948');
$thetextstring = "jjfnj 948";
// replace all spaces with nothing
$thetextstring = str_replace(" ", "", $thetextstring);
// insert a dash after the third character
$thetextstring = substr_replace($thetextstring, "-", 3, 0);
echo $thetextstring;
这给出了所要求的
jjf-nj948
您可以使用
str_replace
删除不需要的空格:
$newString = str_replace(' ', '', $thetextstring);
$newString:
jjfnj948
然后
preg_replace
输入破折号:
$final = preg_replace('/^([a-z]{3})/', '\1-', $newString);
这个正则表达式指令的含义是:
^
([a-z]{3})
\1-
$最终:
jjf-nj948
您的做法是正确的。对于最后一步,即在第三个字符后插入
-
,您可以使用 substr_replace 函数,如下所示:
$thetextstring = 'jjfnj 948';
$string = trim(preg_replace('/\s+/', ' ', $thetextstring));
$result = explode(' ', $thetextstring);
$newstring = substr_replace(implode('', $result), '-', 3, false);
如果您有足够的信心,您的字符串将始终具有相同的格式(字符后跟空格,后跟数字),您还可以减少计算并简化代码,如下所示:
$thetextstring = 'jjfnj 948';
$newstring = substr_replace(str_replace(' ', '', $thetextstring), '-', 3, false);
访问此链接以获取工作演示。
没有正则表达式的老派
$test = "jjfnj 948";
$test = str_replace(" ", "", $test); // strip all spaces from string
echo substr($test, 0, 3)."-".substr($test, 3); // isolate first three chars, add hyphen, and concat all characters after the first three