joev Posted July 24, 2007 Share Posted July 24, 2007 I am trying to create a string which lists receipt numbers that are separated by a commas. I want to remove the last comma after the last receipt number for display: $receipt = ""; for ($i = 0; $i < 3; $i++){ $receiptID = $i; $receipt = settype ($receiptID, string) . ", "; //strval ($receipt); } //$receipt = "325, 326,"; $receipt = preg_replace('/,$/', '', $receipt); //Remove last comma echo $receipt; If I hard code $receipt between double quotes, my preg_replace works fine. If I build $receipt from the for loop, preg_replace leaves the last comma. The problem, I believe, is because $receipt from the loop is not being evaluated as a string. I have tried setting $receipt to a string with settype(), strval(), and (string) without any luck. What am I missing here? Thanks. Link to comment https://forums.phpfreaks.com/topic/61589-converting-to-a-string-for-preg_replace/ Share on other sites More sharing options...
Caesar Posted July 24, 2007 Share Posted July 24, 2007 You're likely making it more complicated than it is. Maybe if you tell us the following we may be able to offer an alternative approach.... 1. What is it you're trying to do? 2. Can you provide an example of what you want the code to output or produce? Link to comment https://forums.phpfreaks.com/topic/61589-converting-to-a-string-for-preg_replace/#findComment-306566 Share on other sites More sharing options...
GingerRobot Posted July 24, 2007 Share Posted July 24, 2007 If you're just trying to remove the last character from your string, which presumably the last comma would be, use substr(). Easier and more efficient than regular expressions. Link to comment https://forums.phpfreaks.com/topic/61589-converting-to-a-string-for-preg_replace/#findComment-306567 Share on other sites More sharing options...
joev Posted July 24, 2007 Author Share Posted July 24, 2007 If you're just trying to remove the last character from your string, which presumably the last comma would be, use substr(). Easier and more efficient than regular expressions. Thanks for pointing me to substr(). substr_replace() does the job. Mahalo Link to comment https://forums.phpfreaks.com/topic/61589-converting-to-a-string-for-preg_replace/#findComment-306589 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.