1

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.

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.

mdixon18
  • 1,199
  • 4
  • 14
  • 35

1 Answers1

2

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:

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

Have a look at the example.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Ah I see, so simple but that's it. Thank you very much. I like that regex tool, is their actually a way to get the indexes of the -> easily? so what position in the string they start and end. – mdixon18 Mar 28 '15 at 17:42
  • So something like preg_match("/\([^\}]+\)/", $string) would get everything within ( ) ?is their a way to limit it to just one result? – mdixon18 Mar 28 '15 at 17:51
  • @Matthew: to get indexes, check http://stackoverflow.com/questions/2451915/php-how-do-i-get-the-string-indexes-of-a-preg-match-all post. As for `/([^\}]+)/`, it will match any character other than `}` 1 or more number of times (greedy) and hold the whole match in Group 1. – Wiktor Stribiżew Mar 28 '15 at 17:56
  • So i guess if you wanted to get the first occurance you would do something like preg_match("/(->)/", $string, $output); and then just get $output[0] or is there a way to limit the regex to the first occurance? – mdixon18 Mar 28 '15 at 17:58
  • @Matthew: To get the first occurrence, you could use `^.*?\K->(?=.*$)` regex. See example at https://regex101.com/r/iZ7tO4/2. – Wiktor Stribiżew Mar 28 '15 at 18:18