FRIHOST FORUMS SEARCH FAQ TOS BLOGS COMPETITIONS
You are invited to Log in or Register a free Frihost Account!


PHP String formatting





davidv
In nearly all of the languages I use, you're able to do something like this:

Code:
name = 'bob'
x = 'hi my name is %s' % name
x = "hi my name is %s", name;


Does PHP have something similar to this?
sonam
I am not sure what do you need but maybe something like this can help:
http://php.net/manual/en/function.sprintf.php

Sonam
Peterssidan
You can use sprintf.
Code:
$name = 'bob';
$x = sprintf('hi my name is %s', $name);


You can also use the use the string concatenation operator (.) to put your string together.
Code:
$name = 'bob';
$x = 'hi my name is ' . $name;


I find the second way easier to work with.
jmraker
And for numbers you can use the number_format function in your string concat
http://us2.php.net/number_format

For fixed size things you can use str_pad
http://us2.php.net/manual/en/function.str-pad.php

There is almost no need to use the printf functions in php. I'm guessing the only time you'd need to use it is for localization where you can't hardcode the word order and you use argument swapping
kacsababa
And you could use double quoted strings, where php parses the string for variables.
Code:
$name = 'bob';
$x = "hi my name is $name";
...but concatenation is usually faster.
davidv
Thanks, Peterssidan. That's exactly what I was looking for.
ogah
Code:
$name = 'bob';
if(isset($name)) { $x = 'hi my name is '.$name; }
else { $x = 'hi i am noname'; }
Adiiforu
you can assign a variable like $name = "bob" and then use it where you want
say with a echo statement or wherever
Related topics
PHP/Mysql - beginner!
Replacement of hexadecimal values in PHP string
Excel SpreadSheet to Website
PHP ristriction on Output
Put gzdeflated item as a string in a PHP file
Sluchawki
Get specific parts of a string
hashing your passwords
execute php string
is it possible to get a html text box to load a .txt file?
The information is not displayed in Textarea
How to use tags for search
What is the best way to make a site?
Python the Hard Way, %s, %r, %d
Reply to topic    Frihost Forum Index -> Scripting -> Php and MySQL

FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2011 Frihost, forums powered by phpBB.