Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add / into the preg_replace pattern

I made this simple function to filter the data. I add the symbols that I allow to be included but I dont know how to add / symbol as well

public function filter($text)
  {
     return preg_replace('/[^^a-zA-Z0-9#@:_(),.!@" ]/','',$text);
  }
like image 277
Ben Avatar asked Apr 03 '12 17:04

Ben


People also ask

What is the difference between preg_replace() and Preg_replace_callback() in PHP?

When preg_replace() is called with the /e modifier, the interpreter must parse the replacement string into PHP code once for every replacement made, while preg_replace_callback() uses a function that only needs to be parsed once.

What is the difference between preg_split () and Preg_replace () in PHP?

preg_split () in PHP – this function is used to perform a pattern match on a string and then split the results into a numeric array preg_replace () in PHP – this function is used to perform a pattern match on a string and then replace the match with the specified text.

How to use PHP preg_replace () in regular expression?

preg_replace () in PHP – this function is used to perform a pattern match on a string and then replace the match with the specified text. Below is the syntax for a regular expression function such as PHP preg_match (), PHP preg_split () or PHP preg_replace (). <?php function_name ('/pattern/',subject); ?>

What is the difference between $pattern and $replacement in PHP?

$pattern: This parameter contains the string element which is used to search the content and it can be a string or array of string. $replacement: It is mandatory parameter which specifies the string or an array with strings to replace.


2 Answers

You can either escape it with a backslash:

preg_replace('/\//' ...);

Or use other characters as delimiters:

preg_replace('|/|' ...);
like image 121
Alex Howansky Avatar answered Oct 04 '22 01:10

Alex Howansky


Simply escape the character with a backslash.

public function filter($text)
  {
     return preg_replace('/[^^a-zA-Z0-9#@:_(),.!@"\/ ]/','',$text);
  }
like image 38
Thomas Wright Avatar answered Oct 03 '22 23:10

Thomas Wright