I'm trying to write regex rules for preg_replace and need to append something to a sub string that contains at least one | and ends in line break.
$str = '"as das dasd", "asrydasd|artysdad|aksda'; // no trailing "
$find = '/^\"*\|*\n$/s';
$replace = $1.'"';
$result = preg_replace($find, $replace, $str);
CodePudding user response:
In your pattern you use an anchor to assert the start of the string. There is also no newline at the end of the string present, and no capture group $1
that you refer to in the replacement.
Your pattern curently matches optional double quotes, then optional pipe chars, a newline and then asserts the end of the string. That can also match an empty string followed by a newline.
If you only want to make sure that the string starts with a double quote and contains at least a single pipe char:
^"[^|\r\n]*\|.*\n$
Looking at the comment in the code, if you want to match a pipe between an inclosed double quote till the end of the string:
"[^"|\r\n]*\|[^"\r\n]*$
Replace with the whole match $0"