weekapaug
weekapaug

Reputation: 332

PHP REGEX find & replace patterns

Trying to construct a regex that will locate a pattern of ANY character followed by double quotes

This regex locates each occurrence properly

(\S"")

Given the example below

$string='"WEINSTEIN","ANTONIA \"TOBY"","STILES","HOOPER \"PETER"","HENDERSON",';
$pattern = '(\S"")';
$replacement = '\\""';
$result=preg_replace($pattern, $replacement, $string);

My result turns out to be

"WEINSTEIN","ANTONIA \"TOB\"","STILES","HOOPER \"PETE\"","HENDERSON"

But I am seeking

"WEINSTEIN","ANTONIA \"TOBY\"","STILES","HOOPER \"PETER\"","HENDERSON"

I understand the replacement is removing/replacing the whole match, but how can I remove all but the first letter rather than completely replacing it?

Upvotes: 0

Views: 31

Answers (1)

Nick
Nick

Reputation: 147146

You can change your pattern to use a positive lookbehind instead so that it doesn't capture the non-space character:

$string='"WEINSTEIN","ANTONIA \"TOBY"","STILES","HOOPER \"PETER"","HENDERSON",';
$pattern = '/(?<=\S)""/';
$replacement = '\\""';
$result=preg_replace($pattern, $replacement, $string);
echo $result;

Output

"WEINSTEIN","ANTONIA \"TOBY\"","STILES","HOOPER \"PETER\"","HENDERSON",

Demo on 3v4l.org

Upvotes: 1

Related Questions