Home > Enterprise >  PHP replace text between two strings in a string
PHP replace text between two strings in a string

Time:10-27

I'm trying to replace a string that comes between 284^A0N,30,24^FD and ^FS ^FO22,314

Example: ^FO22,284^FT22,284^A0N,30,24^FDADRIAN ROY BAGUIO^FS ^FO22,314^FT22

In the above string i want to replace ADRIAN ROY BAGUIO with another name.

I tried the below but no luck.

$search = "/(284\^A0N,30,24\^FD)(.*?)(\^FS \^FO22,314)/";    
echo preg_replace($search,$firstname,$content);

Am i missing anything?

CodePudding user response:

I don't know your $firstname variable but your regex code is not wrong completely but missing (you can test here)

The fully working code is below. I changed the regex a bit

$string = '^FO22,284^FT22,284^A0N,30,24^FDADRIAN ROY BAGUIO^FS ^FO22,314^FT22';

echo preg_replace('/.*(\^FD)([^\^FS] )(.*)/si', '$2', $string);

Output is

ADRIAN ROY BAGUIO

CodePudding user response:

Using your current pattern, you have 3 capture groups, which you can use in the replacement (as you want to replace the content of group 2, you can just match it and have 2 capture groups in total that you want to keep)

$search = "/(284\^A0N,30,24\^FD).*?(\^FS \^FO22,314)/";
$firstname = "Jack";
$content = "^FO22,284^FT22,284^A0N,30,24^FDADRIAN ROY BAGUIO^FS ^FO22,314^FT22";
echo preg_replace($search,"$1$firstname$2",$content);

If you want to write the replacement with your current code, you can change the regex having a match only without any groups.

$search = "/284\^A0N,30,24\^FD\K.*?(?=\^FS \^FO22,314)/";
$firstname = "Jack";
$content = "^FO22,284^FT22,284^A0N,30,24^FDADRIAN ROY BAGUIO^FS ^FO22,314^FT22";
echo preg_replace($search,$firstname,$content);

Output

^FO22,284^FT22,284^A0N,30,24^FDJack^FS ^FO22,314^FT22
  • Related