Jump to content

Converting to a String for preg_replace


joev

Recommended Posts

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
Share on other sites

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
Share on other sites

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