[英]regex to replace any word with two capital letters
I want to replace any word which contains two capital letters . 我想替换任何包含两个大写字母的单词。
here is my string 这是我的字符串
jennie-garth-jennie-garth-inner-city-arts-gala-october-17-2012-If9aSpTW
jennie-garth-jennie-garth3892-H9rDcbY
i want to replace -If9aSpTW with - 我想用 - 替换-If9aSpTW
These -If9aSpTW
varies so I can't use str_replace
. 这些-If9aSpTW
不同,所以我不能使用str_replace
。 I can identify with only two capital letter in one word. 我只能用一个单词中的两个大写字母来识别。 These words are at the end, but these types of words are appearing for 20% of total database values so I can't replace all last words. 这些单词结尾,但这些类型的单词出现在总数据库值的20%,所以我不能替换所有的最后一个单词。
The str_replace
is context unaware, nor can you use substr
since you need to check for 2 uppercase letters in the last non-hyphen chunk of the text. str_replace
是上下文不知道的,你也不能使用substr
因为你需要在文本的最后一个非连字符块中检查2个大写字母。 So you really have to stick to preg_replace
regex based replacement. 所以你真的必须坚持preg_replace
正则表达式替换。
You may use the following regex: 您可以使用以下正则表达式:
preg_replace('/-(?:[^-]*[A-Z]){2,}[^-]*$/', '', $str);
See the regex demo . 请参阅正则表达式演示 。
The pattern matches: 模式匹配:
-
- a hyphen -
- 连字符 (?:[^-]*[AZ]){2,}
- 2 or more occurrences (due to {2,}
limiting quantifier) of a sequence of: (?:[^-]*[AZ]){2,}
- 2次或更多次出现(由于{2,}
限制量词):
[^-]*
[AZ]
- an uppercase [AZ]
- 一个大写字母 [^-]*
- zero or more chars other than -
[^-]*
- 除零以外的零个或多个字符-
$
- end of string $
- 结束字符串 $str = 'jennie-garth-jennie-garth-inner-city-arts-gala-october-17-2012-If9aSpTWe';
echo preg_replace('/-(?:[^-]*[A-Z]){2,}[^-]*$/', '', $str);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.