I'm stuck trying to get the PHP preg_replace to work properly. I want to find all matches of a pattern and replace them with a string. But, for some reason, it's finding only partial matches and replacing all of them. I'm trying to remove the "password" from every line of a text file. The password is always at the end of each line, contains 4 to 8 alpha-numeric characters, and always follows two pipe characters.
Example:
$data = 'A00000001|A00000001|FirstName|LastName|email@address|Role||password'.PHP_EOL;
$data .= 'B00000002|B00000002|FirstName|LastName|email@address|Role||password'.PHP_EOL;
$delim = '|';
$newData = preg_replace("/".$delim.$delim."[a-zA-Z0-9]{4,8}/", $delim.$delim, $data);
echo $newData;
Output:
||||||1|||||||||1|||||||||e||||||||||||e||m||a||i||l||@||a||d||d||r||e||s||s|||||R||o||l||e|||||||||||| ||||||2|||||||||2|||||||||e||||||||||||e||m||a||i||l||@||a||d||d||r||e||s||s|||||R||o||l||e|||||||||||| ||
I've tried many variations with different groupings using parenthesis, putting back to back [a-zA-Z0-9]
patterns instead of {#}. I've tried adding line start ^
and end $
to my pattern. I'm stuck. I know this will end up being something simple to that I'm just overlooking. That's why I need some fresh eyes on this.