简体   繁体   English

php regex-删除短语

[英]php regex - Delete phrase

I have a long string that has imbedded in it: "ABC_1_" and "ABC_2_" and "ABC_3_" etc. 我有一个长字符串嵌入其中: "ABC_1_""ABC_2_""ABC_3_"等。

For example: 例如:

"lorum ipsum ABC_1_ doit more ABC_3_ and so on".

I need to write a PHP preg_replace that will remove the 6 characters ( ABC_xx ) if the first 4 are "ABC_" and return the full remaining string, in my example: 我需要编写一个PHP preg_replace,如果前4个字符是"ABC_" ,它将删除6个字符( ABC_xx ),并返回完整的剩余字符串,在我的示例中:

"lorum ipsum  doit more  and so on". 

Thanks! 谢谢!

Use preg_replace with regular expression: (ABC_.{2} ) 对正则表达式使用preg_replace: (ABC_.{2} )

$string = "lorum ipsum ABC_1_ doit more ABC_3_ and so on";
$pattern = "/(ABC_.{2})/";
$replacement = "";
echo preg_replace($pattern, $replacement, $string);

Try this: 尝试这个:

$s = preg_replace('/\bABC_../', '', $s);

The \\b matches a word boundary, and the dots match any character (apart from new line). \\b匹配单词边界,点匹配任何字符(除了新行)。

Full example: 完整示例:

<?php
$s = 'ABC_1_foo lorum ipsum ABC_1_ doit more ABC_3_ and so on'; 
$s = preg_replace('/\bABC_../', '', $s);
echo $s;
?>

Result: 结果:

foo lorum ipsum  doit more  and so on

(ideone) (ideone)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM