Add a slash to regex

Hi Guys!

I need to add a forward slash (/) to the following regex statement…any ideas how I do it?


function ValidateString($string){
		if(!preg_match('/^[A-Za-z0-9 _-]{1,100}$/i', $string)) {
			return false;
		} else {
			return true;
		}
	}

\/

You can either escape the forward slash with a backslash, like this:
/[1]{1,100}$/i

Or you could use another delimiter and therefore not need to escape it, like this:
#[2]{1,100}$#i


  1. A-Za-z0-9 _-\/ ↩︎

  2. A-Za-z0-9 _-/ ↩︎

I tried both codes, but I get the following error:


Compilation failed: range out of order in character class at offset 15


  1. A-Za-z0-9 _-\/ ↩︎

  2. A-Za-z0-9 _-/ ↩︎

Oops, forgot about the hyphen that should be matched. It needs to be escaped or placed last in the class, therefore my examples would be:
/[1]{1,100}$/i
#[2]{1,100}$#i

I also did away with the A-Z range, since it’s not needed when you’ve got the i modifier at the end (which makes the pattern case insensitive)


  1. a-z0-9 _\/- ↩︎

  2. a-z0-9 _/- ↩︎

Superb! That works perfectly. Any ideas how to implement an ampersand (&) too?


  1. a-z0-9 _\/- ↩︎

  2. a-z0-9 _/- ↩︎

Zaggs, have a read through the character class documentation (and related pages) and I encourage you to have a go yourself.

To make life easier have a play around on an online code editor, which enables you to quickly try different code and see what works. Here’s an example to get you started.