如果后跟特定字符则删除整个单词

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

我的字符串是:

your string here, please/do it by yourself.

我想删除斜杠之前的单词(带有斜杠)并在最后得到这个:

your string here, do it by yourself.

我的代码是:

$string = 'your string here, please/do it by yourself.';
$parsed = preg_replace("\s*\w+\s+(?:w/)", '', $string);

它没有做任何事情(甚至不打印没有更改的字符串)。

php string replace cpu-word
3个回答
1
投票

你的正则表达式没有分隔符,而且没有意义......

“零个或多个空格、一个或多个单词字符、一个或多个空格,后跟一个

w
,然后是
/
”...哈?

$parsed = preg_replace("(\w+/)","",$string);
echo $parsed;

1
投票

不依赖正则表达式的替代解决方案:

<?php

$example = 'your string here, please/do it by yourself.';
$expected = 'your string here, do it by yourself.';

$slashPos = strpos($example, '/');
$spacePos = strrpos($example, ' ', -1 * $slashPos);

$string1 = substr($example, 0, $spacePos + 1); // Add 1 here to not remove space
$string2 = substr($example, (strlen($example) - $slashPos - 1) * -1); // Subtract 1 here to remove /

$result = $string1 . $string2;

var_dump(assert($expected === $result));

https://3v4l.org/XVruS

5.6.38 - 7.3.0 的输出

布尔(真)

参考资料:

http://php.net/manual/de/function.strpos.php

http://php.net/manual/de/function.strrpos.php

http://php.net/manual/de/function.substr.php


0
投票

黑暗阿卜索尔尼特所说的话。您需要分隔符。此外,你的正则表达式(即使有分隔符)会说:“0-无限空格,后跟 1-无限单词字符,后跟 1-无限空格,后跟 'w/'”。

这不是你想要的。您想要删除斜杠 - 和斜杠之前的单词。您需要类似

@\w+/@
(其中
@
符号是分隔符)并将其替换为
''
,例如
preg_replace('@\w+/@', '', $string);
将任何后跟斜线的单词替换为空。

© www.soinside.com 2019 - 2024. All rights reserved.