在 PHP 中用破折号屏蔽字符串

问题描述 投票:0回答:6

我有以下字符串:

$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 个字母后添加分隔符?

php replace
6个回答
4
投票

使用带有

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');

PHP 现场演示


2
投票
$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


2
投票

在不了解更多有关字符串如何变化的情况下,这是适合您任务的有效解决方案:

图案:

~([a-z]{2}) ~  // 2 letters (contained in capture group1) followed by a space

更换:

-$1

演示链接

代码:(演示

$thetextstring = "jjfnj 948";
echo preg_replace('~([a-z]{2}) ~','-$1',$thetextstring);

输出:

jjf-nj948

注意 此模式可以轻松扩展以包含空格前面小写字母以外的字符。

~(\S{2}) ~


1
投票

您可以使用

str_replace
删除不需要的空格:

$newString = str_replace(' ', '', $thetextstring);

$newString:

jjfnj948

然后

preg_replace
输入破折号:

$final = preg_replace('/^([a-z]{3})/', '\1-', $newString);

这个正则表达式指令的含义是:

  • 从行首开始:
    ^
  • 捕获三个 a-z 字符:
    ([a-z]{3})
  • 将此匹配项替换为自身,后跟破折号:
    \1-

$最终:

jjf-nj948

1
投票

您的做法是正确的。对于最后一步,即在第三个字符后插入

-
,您可以使用 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);

访问此链接以获取工作演示。


0
投票

没有正则表达式的老派

$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
© www.soinside.com 2019 - 2024. All rights reserved.