Jump to content

[SOLVED] simple string func not working correctly


scottybwoy

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

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.