简体   繁体   English

Preg匹配字符串以使用正则表达式查找->的所有匹配项

[英]Preg match a string to find all encounters of -> using regular expressions

I'm having a small technical difficulty with a regular expression, I'm trying to look at a string, let's say we have this string: 我在使用正则表达式时遇到了一个小技术难题,我正在尝试查看一个字符串,假设我们有以下字符串:

$string = "error->400";

And another string: 还有另一个字符串:

$string = "error->debug->warning";

As an example, I'm basically trying to do a preg_match() that returns true on any instances of -> within it. 举个例子,我基本上是想做一个preg_match() ,在其中的任何->实例上返回true。

This is my attempt but I don't understand why it doesn't work: 这是我的尝试,但我不明白为什么它不起作用:

preg_match("/^[->]*$/", $string);

Is there a general rule for custom characters that i'm generally missing? 我普遍缺少的自定义字符是否有一般规则?

Thanks. 谢谢。

Right now, ^[->]*$ matches any number of "-" or ">" characters, from the beginning to end. 现在, ^[->]*$从头到尾匹配任意数量的“-”或“>”字符。 You must use a group, not a character class, and anchors are not necessary. 您必须使用组,而不是角色类,并且不需要锚。 Use this to check if "->" is present in the $string : 使用它来检查$string是否存在“->”:

 preg_match("/(->)/", $string);

Have a look at the example . 看这个例子

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

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