Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.