Page 1 of 1
Convert strings to var-compatible values
Posted: Fri May 06, 2005 7:40 am
by eromein
Hi,
I'm look for a way to convert strings to php variable names. So I need to delete all characters that can not be used in php vars and I need to replace spaces with underscores.
Example:
String "No." needs to be converted to "no".
String "Phone No." need to be converted to "phone_no".
ect...
Could somebody please help me with this?
Thanks,
Kind regards
Emiel Romein
The Netherlands
Posted: Fri May 06, 2005 7:54 am
by Skara
php will take uppercase letters. I believe it will also take spaces in indices.
e.g. $foo['Example Key']
in any case, you'll simply need the following:
Code: Select all
$string = str_replace(' ','_',strtolower($string));
Posted: Fri May 06, 2005 7:58 am
by eromein
Thing is I'm using Smarty (smarty.pear.net).
In Smarty I need to define an array like foo['bar'] as foo.bar.
If my array index = "Phone No." then in Smarty this would look like foo.Phone No. As you can imagen, this will end up in a synax error. So I need to convert the index names to, in this case, phone_no dso I can use foo.phone_no in Smarty.
Hope I'm clear enough.
Posted: Fri May 06, 2005 8:01 am
by Skara
ah, yeah ok. the above code'll work fine. I'd watch for weird characters, though.
Posted: Fri May 06, 2005 8:10 am
by eromein
Thanks,
But it's all about the weird charaters. Code above is what I got already. I need a way to delete all weird charaters and replace spaces.
I'd hoped this could all be done in one statement.
Kind regards,
Emiel Romein
Netherlands, the
Posted: Fri May 06, 2005 8:58 am
by phpScott
be the first to post what you are looking for in the new regex forum as that is what I believe you are looking for.
I would help but i suck at regex expressions.
Posted: Fri May 06, 2005 9:55 am
by Skara
the above code
does replace spaces. But yeah, for weird chars, a regex would be the best.
