PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, November 20, 2022

[FIXED] how to use regex special characters in pattern in preg_replace

 November 20, 2022     php, preg-replace, regex     No comments   

Issue

I am trying to replace 2.0 to stack,

but the following code replace 2008 to 2.08

Following is my code:

$string = 'The story is inspired by the Operation Batla House that took place in 2008 ';
$tag = '2.0';
$pattern = '/(\s|^)'.($tag).'(?=[^a-z^A-Z])/i';
echo preg_replace($pattern, '2.0', $string);

Solution

Use preg_quote and make sure you pass the regex delimiter as the second argument:

$string = 'The story is inspired by the Operation Batla House that took place in 2008 ';
$tag = '2.0';
$pattern = '/(\s|^)' . preg_quote($tag, '/') . '(?=[^a-zA-Z])/i';
//                     ^^^^^^^^^^^^^^^^^^^^^
echo preg_replace($pattern, '2.0', $string);

The string is not modified. See the PHP demo. The regex delimiter here is /, thus it is passed as the 2nd parameter to preg_quote.

Note that [^a-z^A-Z] matches any chars but ASCII letters and ^ since you added the second ^ in the character class. I changed [^a-z^A-Z] to [^a-zA-Z].

Also, the capturing group at the start may be replaced with a single lookbehind, (?<!\S), it will make sure your match occurs only at the string start or after a whitespace.

If you expect to also match at the end of the string, replace (?=[^a-zA-Z]) (that requires a char other than a letter immediately to the right of the current location) with (?![a-zA-Z]) (that requires a char other than a letter or end of string immediately to the right of the current location).

So, use

$pattern = '/(?<!\S)' . preg_quote($tag, '/') . '(?![a-zA-Z])/i';

Also, consider using unambiguous word boundaries

$pattern = '/(?<!\w)' . preg_quote($tag, '/') . '(?!\w)/i';


Answered By - Wiktor Stribiżew
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing