Julian S
Julian S

Reputation: 381

Why are regular expressions wrapped in forward slashes

I'm diving into regex.

$subject = "abcdef";
$pattern = '/^def/';
preg_match($pattern, substr($subject,3), $matches, PREG_OFFSET_CAPTURE);
print_r($matches);

I see that forward slashes are used to mark the beginning and end of a regular expression. I'm trying to find out why that is the case. I can't find any documentation about these forward slashes.

Upvotes: 3

Views: 1056

Answers (2)

bjfletcher
bjfletcher

Reputation: 11518

For conventional/traditional reasons. Often we'd have three parts to the regex, the pattern, the substitution, and the modifiers. For example, the substitution command:

s/Hello/G'day/g

has three components: the Hello which is the pattern - we want to find "Hello", the G'day which is the substitution - we want to replace "Hello" with "G'day", and g which are the modifiers - in this case, g means to do it as many times as possible and not just once.

With some languages, they have the components as separate arguments rather than being delimited using slashes.

Often if you see it without any slashes, it means it's the pattern. If for some reason a language surrounds a pattern with slashes, you know it means it's the pattern.

Hope this helps. :)

Upvotes: 2

hwnd
hwnd

Reputation: 70732

The first and most important thing to know about the preg_...() functions is that they expect one character delimiter on each side of the pattern. For the delimiter, you can choose any character apart from backslashes and spaces. The forward slash is the most used delimiter.

And, everything is stated pretty clear in the documentation referencing delimiters.

Upvotes: 3

Related Questions