Jump to content

Recommended Posts

Hi I want to check if a specific character is at the begginign and end of some string data, then if it exists, chop it off.  This is what I have, but it doesn't work.  P.S. is there a simpler way to do it :

$f_char = substr($products_description, 0, 1);
$l_char = substr($products_description, -1);

if (($f_char == '"') && ($l_char == '"')) {
echo "cleaning description";
$len = strlen($products_description);
$products_description = substr($products_description, 1, $len -1);
}

You can actually use the bracket operators on a string, so I'd do it like this...

 

$first = $str[0]; // First char
$last = $str[strlen($str)-1]; // Last char
if($first == '"' && $last == '"') {
   $str = substr($str, 1, -1);
}

 

The reason yours didn't work is because you have to remember the third param of substr() is the number of characters to get... so if you go strlen() - 1 and you started at index 1 (second char), you'll go to the end of the string. You'd need to do strlen()-2 to chop an extra char off of the end.

<?php
$products_description = "\" TESTING \"";
$f_char = substr($products_description, 0, 1);
$l_char = substr($products_description, -1);

echo $f_char . " - f_char<br />" . $l_char . " - l_char<br />";

if (($f_char == '"') && ($l_char == '"')) {
   echo "cleaning description";
   $len = strlen($products_description);
   $products_description = substr($products_description, 1, $len -2);
}
echo $products_description . "<Br /><Br />";
?>

 

Simple debugging would of found that you needed to do $len - 2 since the substr is 0 index based.

Do note that using trim() will remove more than one consecutive quote from the edge of the string, and will still remove a quote from the beginning of the string if there is not a matching one at the end of the string, and vice versa. This is a bit different than your current implementation, but if you don't mind these differences trim() would be more efficient.

Thanks for your help.  Yeah trim() isn't quite what I was looking for.  I had done debugging first which is why I couldn't find the error.  My problem was that I was using someone else's script and it was working on the wrong data. lol.  Is sorted now, thanks

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.