preg_replace: add number after backreference
The solution is to wrap the backreference in ${}
.
$out = preg_replace( '/([aeiou])/', '${1}8', $in);
which will output a8bcde8fghi8j
See the manual on this special case with backreferences.
RegEx backreference followed by numbers
I found my answer here
Turns out all I had to do was to wrap the back-reference in curly brackets
Solution
Sublime: Find What: ([a-zA-Z]*)2013 Replace With: ${1}2014
PHP: preg_replace('~([a-zA-Z]*)2013~', '${1}2014', $file_contents);
Named backreferences with preg_replace
They exist:
http://www.php.net/manual/en/regexp.reference.back-references.php
With preg_replace_callback:
function my_replace($matches) {
return '/user/profile/' . $matches['id'];
}
$newandimproved = preg_replace_callback('#^user/(?P<id>[^/]+)$#Di', 'my_replace', $string);
Or even quicker
$newandimproved = preg_replace('#^user/([^/]+)$#Di', '/user/profile/$1', $string);
Avoid backreference replacement in php's preg_replace
Escape the dollar character before using a character translation (strtr
):
$repValue = strtr('$0.0 $00.00 $000.000 $1.1 $11.11 $111.111', ['$'=>'\$']);
For more complicated cases (with dollars and escaped dollars) you can do this kind of substitution (totally waterproof this time):
$str = strtr($str, ['%'=>'%%', '$'=>'$%', '\\'=>'\\%']);
$repValue = strtr($repValue, ['%'=>'%%', '$'=>'$%', '\\'=>'\\%']);
$pattern = '/{{' . strtr($field, ['%'=>'%%', '$'=>'$%', '\\'=>'\\%']) . '}}/';
$str = preg_replace($pattern, $repValue, $str );
echo strtr($str, ['%%'=>'%', '$%'=>'$', '\\%'=>'\\']);
Note: if $field
contains only a literal string (not a subpattern), you don't need to use preg_replace
. You can use str_replace
instead and in this case you don't have to substitute anything.
Capture Group Not Captured in Preg_replace Replacement
In fact, the issue is the concatenation of the capture groups with time()
. Use this version instead:
$f = 'IMG_1474.PNG';
$output = preg_replace('/(.*)([.][^.]+$)/', '${1}' . time() . '${2}', $f);
echo $output;
This prints:
IMG_14741604148316.PNG
^^^^^^^^^^ second since epoch (1970-01-01)
To understand why this is happening, we have to consider that variable substitution occurs before the preg_replace
function call does. So your concatenated replacement term:
'$1' . time() . '$2'
actually first becomes:
'$1' . '1604148623' . '$2'
which is:
'$11604148623' . '$2'
The "first" capture group here is probably being interpreted as $11
(or $116
, etc.), and is not defined. This is why you are currently only getting the second capture group, but the first one is empty. The solution I suggested uses ${1}
which preserves the capture group reference so it is available during the preg_replace
call as you intend.
PHP preg_replace add tag to digit in string
You would want to use a backreference, like this:
$formula = preg_replace('/(\d+)/','<sub>\1</sub>',$formula);
I added the //
as delimiters to make it a proper pattern. I also added a +
so that it would place all connecting digits in the same <sub>
tag.
Using preg_replace to back reference array key and replace with a value
You need to use the /e
eval flag, or if you can spare a few lines preg_replace_callback
.
$string = preg_replace(
'|http://mysite.com/script.php\?fruit=([a-zA-Z0-9_-]*)|e',
' "http://mysite.com/" . $fruitArray["$1"] ',
$string
);
Notice how the whole URL concatenation expression is enclosed in single quotes. It will be interpreted as PHP expression later, the spaces will vanish and the static URL string will be concatenated with whatever is in the fruitArray.
PHP preg_replace Backreferencing
\w is only [A-Za-z0-9_] so you need to handle other characters, spaces etc. Either add all the types you need or maybe match everything up to ' %>'.
You can use preg_replace and then get the file size afterwards or use preg_replace_callback.
A couple of examples:
$oldStr = "<% size_../files/file with spaces.rar %>";
$size1 = preg_replace_callback("/<% size_([\w\.\/\s]+) %>/",
function ($matches) {
return filesize($matches[1]);
},
$oldStr);
$newStr = preg_replace("/<% size_(.+) %>/", "$1", $oldStr);
if (is_file($newStr)) {
$size2 = filesize($newStr);
} else {
//not a file
}
PHP: preg_replace replace abbreviation using backreferences
The idea is to find all single letter + dot \b[a-z]\.
followed by an other single letter + dot.
you can use:
$txt = preg_replace('~\b[a-z]\.(?=[a-z]\.)~i', '$0\,', $txt);
where (?=..)
is a lookahead that performs only a check (followed by)
Second solution:
$txt = preg_replace('~(?<=\b[a-z]\.)(?=[a-z]\.)~i', '\,', $txt);
Instead of a backreference to the whole match, I use a lookbehind (?<=..)
. Nothing is captured and the regex engine is at the good offset to add \,
Related Topics
Difference Between Array_Map, Array_Walk and Array_Filter
Deleting All Files from a Folder Using PHP
How to Protect from Downloading a Video from a Site
Why Don't PHP Attributes Allow Functions
What's an Actual Use of Variable Variables
How to Get the Character from Unicode Code Point in PHP
Unserialize PHP Array in JavaScript
PHP Commands Out of Sync Error
Remove .PHP Extension (Explicitly Written) for Friendly Url
PHP Remove Special Character from String
Two Simultaneous Ajax Requests Won't Run in Parallel
Package 'Php5-Gd' Has No Installation Candidate