Jump to content

Preg_replace help


MuseiKaze

Recommended Posts

Hi there, im writing part of a code to replace certain parts of a string in a csv file.

For example:

 

I want something like this

 

Product Name|Product ID|Price

to look like this

Product Name","Product ID","Price

 

Ive tried using preg_replace and ereg_replace but I cant seem to get either of them to work.

 

$replace = preg_replace("#|#","\",\"", $content);

 

This is what I have so far, but this just adds "," between each letter. Could someone please explain the correct way which I can do this?

 

Thanks heaps

Link to comment
https://forums.phpfreaks.com/topic/190054-preg_replace-help/
Share on other sites

The reason you're getting that result is because | in regular expressions means the literal "or". So you'd need to escape that character ( #\|# ).

 

But in this specific case I wouldn't suggest using regex. PCRE functions consume a lot of memory and should be avoided when possible. Unless you need match complex patterns you should find an alternative. In your case you can just use str_replace

 

$replace = str_replace('|', '","', $content);

Link to comment
https://forums.phpfreaks.com/topic/190054-preg_replace-help/#findComment-1002702
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.