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

Sunday, November 20, 2022

[FIXED] How to use $1 twice

 November 20, 2022     php, preg-replace     No comments   

Issue

I want to know how can I use the value of (.*?) twice? for example:

$data = preg_replace("/<d>\s*(\s*(.*?)\s*)</d>/i", "F: $1, S: $1", $data);

this code above returns the value I use (for example: Hello) and returns: F: , S: Hello, but I want it to return F: Hello, S: Hello

Here's the code that isn't working:

"MySQLi\s*~\s*Escape\s*(\s*.*?\s*)", "$1 = mysql_real_escape_string$1", "MySQLi~Escape('Hi');" outputs:

 = mysql_real_escape_string('Hi');

Solution

What you need is the U modifier.

Try it here:

$res = preg_replace("/MySQLi\s*~\s*Escape\s*((\s*.*?\s*))/U", "$1 = mysql_real_escape_string$2", "MySQLi~Escape('Hi');");
var_dump($res);

output:

string(41) "('Hi'); = mysql_real_escape_string('Hi');"

From the official PHP's documentations:

U (PCRE_UNGREEDY)

This modifier inverts the "greediness" of the quantifiers so that they are not greedy by default, but become greedy if followed by ?. It is not compatible with Perl. It can also be set by a (?U) modifier setting within the pattern or by a question mark behind a quantifier (e.g. .*?).



Answered By - user2342558
Answer Checked By - Candace Johnson (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