如果单词包含特定字符串,则删除整个单词 [英] Remove entire word if the word contains specific string

查看:53
本文介绍了如果单词包含特定字符串,则删除整个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想执行以下操作,最好使用 PHP:

I would like to do the following, preferably with PHP:

如果单词的一部分包含特定字符串,则删除整个单词.这应该不区分大小写并且可以多次工作,例如在大文本上.

Remove an entire word if a part of the word contains a specific string. This should be case insensitive and work multiple times, e.g. on a large text.

伪代码:

match = "www."
lots_of_random_text = "... hello and welcome to www.stackoverflow.com! blah blah"
result = magic_function(lots_of_random_text, "www.")

结果现在应该等于:"...你好,欢迎来到 blah blah".

我将如何以最有效的方式做到这一点?

How would I do this the most efficient way?

推荐答案

正则表达式似乎适合这项任务.查看 preg_match 的文档主要 PCRE 文档 以获得完整概述.

It seems that a regular expression would suit this task. Check out the docs for preg_match to start with, or the main PCRE docs for a complete overview.

php> $text="hello and welcome to www.stackoverflow.com snout pickle and while you're here, check out a unicorn at www.unicornmagicfairywonderland.net!";
php> $cleaned_text=preg_replace('#www\.[\w\d]+\.(com|net|org)#','',$text);
php> echo $cleaned_text;    
hello and welcome to  snout pickle and while you're here, check out a unicorn at !

关键部分是#www.[\w\d]+.(com|net|org)#".这意味着匹配任何以 www. 开头、包含任意数量的单词字符或数字并以 .com、.net 或 .org 结尾的字符串.

The key part is the '#www.[\w\d]+.(com|net|org)#'. That means match any string that starts with www.,has any number of word characters or digits, and ends with .com, .net or .org.

如果您尝试替换任何 URL,则表达式将比这复杂得多,因此请注意这是不完整的.您需要确保它匹配以 http://开头的单词,没有 www.或者有一个不同的子域,并以 .co.uk 或 .edu 等其他域结尾,对吗?

If you're trying to replace any URL, the expression is going to be much more complex than this, so be warned this is incomplete. You'd want to make sure it matches words that start with http://, have no www. or have a different subdomain, and end with other domains like .co.uk or .edu, right?

正则表达式通常很复杂,而且很难正确处理.您可能会发现 www.regular-expressions.info 很有帮助.

Regular expressions are in general, complex and tough to get right. You may find www.regular-expressions.info helpful.

这篇关于如果单词包含特定字符串,则删除整个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆