Sergei Veit
Sergei Veit

Reputation: 61

Replace all dot characters between single quotes using preg_replace

I have next

$pattern = "~'(.*?)\\.(.*?)'~i";
$replacement = "'\\1\\\\x2e\\2'"
$subject = "window.location.href='example.com'";
preg_replace($pattern, $replacement, $subject);

It work nice and I got

"window.location.href='example\x2ecom'"

But if I have

$subject = "window.location.href='www.example.com'";

or

$subject = "window.location.href='www.example.example.com'";

I have dots in string.

Please help with $replacement

UPDATE:

I need get string where all dots in '' should be \x2e

If I have

"window.location.href='www.example.example.com'"

then I need

"window.location.href='www\x2eexample\x2eexample\x2ecom'"

Upvotes: 2

Views: 651

Answers (2)

Josh Crozier
Josh Crozier

Reputation: 240868

One option is to use a positive lookahead and a negated character class in order to only match the literal . characters at the end of the string between the ' characters:

$pattern = "~\\.(?=[^']*'$)~i";

Explanation:

  • \\. - Match the . character literally.
  • (?= - Start of a positive lookahead.
  • [^']*'$ - Match the preceding character literally, ., if it is followed by zero or more non-' characters followed by ' at the end of the string.
  • ) - End of the positive lookahead.

In other words, only the . characters between ' characters at the end of your string will be matched.

Example Here

$pattern = "~\\.(?=[^']*'$)~i";
$replacement = "\\x2e";
$subject = "window.location.href='www.example.com'";
echo preg_replace($pattern, $replacement, $subject);

Output:

"window.location.href='www\x2eexample\x2ecom'"

Based on your comment(s) below:

If there are multiple occurrences of the substring window.location.href='.*', then you could use the alternation (?:$|;) so that it matches up until the last ; or the end of the string, $.

$pattern = "~\\.(?=[^']*'(?:$|;))~i";

Example Here

$pattern = "~\\.(?=[^']*'(?:$|;))~i";
$replacement = "\\x2e";
$subject = "window.location.href='.www.test.test.com.'; window.location.href='.www.test.test.com.';";
echo preg_replace($pattern, $replacement, $subject);

Output:

"window.location.href='\x2ewww\x2etest\x2etest\x2ecom\x2e'; window.location.href='\x2ewww\x2etest\x2etest\x2ecom\x2e';"

Upvotes: 2

Quixrick
Quixrick

Reputation: 3200

Here's an idea using preg_replace_callback instead of preg_replace. It allows you to pass in a function to operate on each match.

$subject = "window.location.href='example.com.com.com.com.com'";

$subject = preg_replace_callback("~(?<=')(.*?)(?=')~", function($m) {return preg_replace('~\.~', '\x2e', $m[1]);}, $subject);

print $subject;

This will output:

window.location.href='example\x2ecom\x2ecom\x2ecom\x2ecom\x2ecom'

Basically what we're doing here is matching everything inside of the ticks. Then, when it finds a match, it swaps out each dot for \x2e within that string.

Here is a working demo:

http://ideone.com/eYh2rO

Upvotes: 1

Related Questions