Anonymous
Anonymous

Reputation: 4632

How to escape slashes in regex?

I've made some regex to test for a YouTube embedded video:

/^(http:\/\/www\.youtube\.com\/embed\/)[^\/\s\\]+$/

It works for what I expect when I test it, but the problem though is that I need to pass that regex as a string to some function. Particularly I'm using htmlawed, where I pass a following string to a function:

func('iframe=-*,src(match="/^(http:\/\/www\.youtube\.com\/embed\/)[^\/\s\\]+$/")');

The problem is that the above regex sort of works, but it just ignores the slashes, and accepts anything in place of them.

That is why I suspect that there is a problem with escaping.

I would appreciate if you could advice some alternative ways of escaping these slashes and backslashes... there must be some way?

Upvotes: 2

Views: 7072

Answers (2)

Tim Pietzcker
Tim Pietzcker

Reputation: 336108

In PHP, you can also use a different regex delimiter:

~^(http://www\.youtube\.com/embed/)[^/\s\\\\]+$~

Upvotes: 0

Bergi
Bergi

Reputation: 664247

If you have a string, you will need to escape the backslashes (and quotes) for the string literal. Or, depending on how the function builds the regex from the string, you might not need to escape slashes at all (I don't think so here).

"iframe=-*,src(match=\"/^(http:\\/\\/www\\.youtube\\.com\\/embed\\/)[^\\/\\s\\\\]+$/\")"

Upvotes: 4

Related Questions