Removing Starting and Ending Single Quotes from Variable


I’m attempting to strip out the starting and ending quotation marks (if any) from a variable using REGEX.

The following code successfully removes double-quotes;[/FONT]

// Parse Data
	// $ex_displayname
			$ex_displayname_PAR = $ex_displayname;
			$ex_displayname_PAR = preg_replace('/^"/','',$ex_displayname_PAR);
			$ex_displayname_PAR = preg_replace('/"$/','',$ex_displayname_PAR);

However the version I attempted for single quotes is doing nothing;

// Parse Data
    // $ex_displayname
            $ex_displayname_PAR = $ex_displayname;
			$ex_displayname_PAR = preg_replace("/^'/","",$ex_displayname_PAR);
			$ex_displayname_PAR = preg_replace("/'$/","",$ex_displayname_PAR);

[FONT=“Georgia”]Can anyone suggest what might be wrong?


this is working fine on my local xampp server and successfully removes the single quotes

            $ex_displayname_PAR = "'qwerty'";
            echo '<br />before: '.$ex_displayname_PAR;
            $ex_displayname_PAR = preg_replace("/^'/","",$ex_displayname_PAR);
            $ex_displayname_PAR = preg_replace("/'$/","",$ex_displayname_PAR);
            echo '<br />after: '.$ex_displayname_PAR;

I don’t see the need to use regex when you have [fphp]trim[/fphp]

$ex_displayname_PAR = trim($ex_displayname_PAR, '"\\'');


[FONT=“Georgia”]HAHAHA!.. “Have you tried trim(); ?”

Thanks for the heads up, I’ll give it a go.


It does work. I was going to make a comment, then thought “Hmm - I better test this before I comment and look like an @rse”. :lol:


Weird, it’s not making any changes at all when I test. Unless there’s something else going wrong along the way.

Anyways, if trim() can do it, that’d be easier; One line of code vs. four.

Going to try it out in a few minutes.


I’m going out on a limb here… but, have you tried trim() ?

Maybe there are spaces next to the single quotes?
In that case, you should trim() first to remove the spaces.

It shouldn’t matter with a suitable character mask.

  trim(' "foo" ', '"\\' ')

#string(3) "foo"

My test was very simple …

echo "<pre>";
$var = " 'My name is John O'Shea, isn't it?' ";
echo $var . "\
$var = trim ($var, ' \\'');
echo $var . "</pre>";

Thanks, everyone. Yes, trim() worked.

[FONT=“Georgia”]I think that needs to be on a Sitepoint T-shirt.