Flynn
Flynn

Reputation: 6181

Writing a regular expression with special characters

As preface, I am new to (and really bad at) writing regular expressions.

I am trying to use a regular expression in the PHP function preg_split, and am looking to delineate by

*
**
`

I'm having trouble because these characters are commands. How can I write a regular expression to do this?

Upvotes: 1

Views: 87

Answers (2)

hwnd
hwnd

Reputation: 70722

For PCRE and other so-called compatible flavors, you must escape these outside character classes.

. ^ $ * + ? () [ { \ |

The backtick has no special meaning, so you don't need to escape it.

preg_split('/\*{1,2}|`/', $text);

See Demo

Note: For future reference, you may want to look into using preg_quote()

preg_quote() takes str and puts a backslash in front of every character that is part of the regular expression syntax. This is useful if you have a run-time string that you need to match in some text and the string may contain special regex characters.

Upvotes: 3

gontrollez
gontrollez

Reputation: 6538

preg_split("(?:\*{1,2}|\`)", $string);

Upvotes: -1

Related Questions