如何从 PHP 字符串中单独删除特定的特殊字符?

发布于 2024-11-08 17:39:33 字数 324 浏览 0 评论 0原文

我有一个像下面这样的字符串,

《印度斯坦时报》,2009 年 10 月,评论者 著名艺术评论家谈她的独奏 斋浦尔贾瓦哈卡拉展览 Kendra'th,2009 年 9 月 23 日至 29 日。“许多 她的画,包括她自己 肖像、人文压力 奇异的困境和漫无目的”

在上面的字符串中我需要删除以下字符

, " ' - .

是否有任何字符串函数可以用来删除这些字符?

I have a string like below,

Hindustan Times, Oct 2009, Review by a
well known Art critic on her solo
exhibition at Jaipur, Jawahar Kala
Kendra'th, 23-29th Sep 2009. "Many of
her paintings including her self
portrait, stress in humanities
singular plight and aimlessness"

In the above string I need to remove the following characters

, " ' - .

Are there any string functions I can use to remove these characters?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

梦魇绽荼蘼 2024-11-15 17:39:33

您可以使用 str_replace 替换字符数组

$str = "Hindustan Times, Oct 2009, Review by a well known Art critic on her solo exhibition at Jaipur, Jawahar Kala Kendra'th, 23-29th Sep 2009. \"Many of her paintings including her self portrait, stress in humanities singular plight and aimlessness";
$search     = array(',', '"', "'", '-', '.');
$clean      = str_replace($search, ' ', $str); 
echo $clean; 

You can use str_replace to replace an array of characters

$str = "Hindustan Times, Oct 2009, Review by a well known Art critic on her solo exhibition at Jaipur, Jawahar Kala Kendra'th, 23-29th Sep 2009. \"Many of her paintings including her self portrait, stress in humanities singular plight and aimlessness";
$search     = array(',', '"', "'", '-', '.');
$clean      = str_replace($search, ' ', $str); 
echo $clean; 
不醒的梦 2024-11-15 17:39:33

或者,您可以选择删除所有非字母数字或空格的字符,而不是列出您不需要的所有字符:

preg_replace("/[^A-Za-z0-9\s]/", "", $str);

当然,这会删除所有标点符号,也许比您想要的更多字符。

Alternatively, you can opt to strip out all characters that aren't alphanumeric or spaces, instead of listing all the characters you don't want:

preg_replace("/[^A-Za-z0-9\s]/", "", $str);

Of course, this would strip out all punctuation, and perhaps more characters than you want.

揽清风入怀 2024-11-15 17:39:33

使用 preg_replace ,并将所需的集合替换为空字符串。

use preg_replace , and replace the set you want with empty string.

执着的年纪 2024-11-15 17:39:33

JohnP 有正确的方法使用str_replace()。经验法则基本上是只使用正则表达式,而其他字符串方法则不能(或者至少不能很好)。

但是,如果您想使用正则表达式,也可以这样做。

您可以在字符类中输入这些字符,注意转义字符串分隔符,并以按字面意思而不是范围的方式使用 -

preg_replace('/[,"\'.-]+/', '', $str);

Ideone

JohnP has the right way with using str_replace(). The rule of thumb is basically only use a regex where other string methods won't do (or at least not nicely).

However, if you want to use a regex, you could do that too.

You would enter those characters in a character class, taking note to escape the string delimiter and also to use - in a manner where it will be taken literally, not as a range.

preg_replace('/[,"\'.-]+/', '', $str);

Ideone.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文