Convert strings to var-compatible values

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
eromein
Forum Newbie
Posts: 7
Joined: Fri May 06, 2005 7:35 am

Convert strings to var-compatible values

Post 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
User avatar
Skara
Forum Regular
Posts: 703
Joined: Sat Mar 12, 2005 7:13 pm
Location: US

Post 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));
eromein
Forum Newbie
Posts: 7
Joined: Fri May 06, 2005 7:35 am

Post 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.
User avatar
Skara
Forum Regular
Posts: 703
Joined: Sat Mar 12, 2005 7:13 pm
Location: US

Post by Skara »

ah, yeah ok. the above code'll work fine. I'd watch for weird characters, though.
eromein
Forum Newbie
Posts: 7
Joined: Fri May 06, 2005 7:35 am

Post 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
User avatar
phpScott
DevNet Resident
Posts: 1206
Joined: Wed Oct 09, 2002 6:51 pm
Location: Keele, U.K.

Post 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.
User avatar
Skara
Forum Regular
Posts: 703
Joined: Sat Mar 12, 2005 7:13 pm
Location: US

Post by Skara »

the above code does replace spaces. But yeah, for weird chars, a regex would be the best. ;)
Post Reply