I'm probably missing something really obvious.
While converting a bunch of string before inserting them in a array I noticed some string where different among each other because of first char being uppercase or not. I decided then to use ucfirst to make first character uppercase but it seems it doesn't work properly, I have had a look around on the web trying to figure out why this is happening but I had no luck.
$produtto = 'APPLE';
echo ucfirst($produtto);
//output: APPLE
If I use instead mb_convert_case
$produtto = 'APPLE';
echo mb_convert_case($produtto, MB_CASE_TITLE, "UTF-8");
//Output: Apple
ucfirst() only looks at the first character so you should convert to lowercase first.
Use this:
$produtto = 'APPLE';
echo ucfirst(strtolower($produtto));
//output: Apple
In the first case I assume you would first need to turn them lowercase with strtolower, and then use ucfirst on the string.
http://php.net/manual/en/function.mb-convert-case.php
MB_CASE_TITLE is not the same as ucfirst(). ucfirst is only interested in the first character. MB_CASE_TITLE is about the whole string and making it an initial capital string.
read the manual! APPLE = uppercase.. so ucfirst does nothing.
www.php.net/ucfirst
$foo = 'hello world!';
$foo = ucfirst($foo); // Hello world!
$bar = 'HELLO WORLD!';
$bar = ucfirst($bar); // HELLO WORLD!
$bar = ucfirst(strtolower($bar)); // Hello world!
Related
I'm a designer trying to upgrade myself into a coder-designer. Lately I've been looking into some PHP codes and manuals, then I ran into an example code for the eval() function :
<?php
$string = 'cup';
$name = 'coffee';
$str = 'This is a $string with my $name in it.';
echo $str. "\n";
eval("\$str = \"$str\";");
echo $str. "\n";
?>
This is an example code of eval() function in official PHP website, and although it did help me understand the eval() function, I can't figure out how the example code works. to be more specific, I can't understand why
("\$str = \"$str\";")
results in a merged string.
I really can't figure out why this should work.
Ok, here is what we have:
eval("\$str = \"$str\";")
Look, the string is in double quotes: it means that the $ character will be interpreted as a variable start. So we screen this character with a backslash: \$, then it will "mean" just a normal dollar sign. Also, the double quotes inside the string had to be screened too.
In the end we are getting this string: (I changed the quotes to single so $ dont confuse you): '$str = "$str";'. Look, it looks more like a normal code now :)
Evaling it, PHP will do the following (I removed the outer quotes for convenience):
eval( $str = "$str" );
Notice the double quotes here, too. It means that the variable inside, again, will be parsed/interpreted.
As $str was originally == 'This is a $string with my $name in it.', it will be inserted into the expression, and now it will look like:
$str = "This is a $string with my $name in it.";
And, again, double quotes! It parses and substitutes variables $name and $string, giving us at the end:
$str = "This is a cup with my coffee in it."
Voila!
A mindbreaker, but a really good example to learn the mechanisms.
you should get two console.log like this
This is a $string with my $name in it.';
This is a $cup with my $coffe in it.';
Why? well first you print the value, of $str , without eval, and later, you eval them, basically this happens,
First.
Print $str, without eval.
This is a $string with my $name in it.';
Second
this piece of code, runs eval("\$str = \"$str\";");
Eval replace $string and $name. with the 2 new variables values, which are $cup and $coffe
Hope you get it
I know how to find a (part of a) string and change that, but the problem is, the part I have to change is variable in length and in characters.
example
$string = "bla1bla2bla3textbla4bla5";
normaly I should explode to filter out text, but because "bla3" is different to "bla4", I have no idea how to explode or find "text", however it's always between "bla3" and "bla4", but "text" is variable aswel as bla1, 2 and 5.
after I find "text" I need to replace it by an other text.
Perhaps I can find this on google, but the problem is, I have no clue how to discribe it.
You can use preg_split() for this. I can't remember the exact regex for this, but it should be something like:
$text = preg_split("/[0-9]*/", "bla1bla2bla3textbla4bla5");
Using explode:
$parts = explode('text',$string); //splits it into two parts, removing `text`
$string = $parts[0] .'replacement'. $parts[1]; //glue the parts together with replacement
Using str_replace:
$string = str_replace('text','replacement');
And as for describing your problem: I'd try googling something like php replace substring.
ok, some examples.
$string1 = "bla1bla2bla3textbla4bla5";
find "text" in $string and replace it by "example"
output:
$string1 = "bla1bla2bla3examplebla4bla5";
other example
$string2 = "I bla3don'tbla4 know how to do it"
find "don't" in $string and replace it by "example"
output:
$string2 = "I bla3examplebla4 know how to do it"
other example
$string3 = "textbla3textbla4text"
find "text" but only the one between bla3 and bla4 and replace it by "example"
output shoud be something like
$string3 = "textbla3examplebla4text"
hope this makes it more clear.
so the part of bla3 and bla 4 stay the same, but anything else can change.
I would like to know when and why should I use {$var}
echo "This is a test using {$var}";
and when (and why) should I use the simple form $var
echo "This is a test using $var";
You would use the latter when a) not accessing an object or array for the value, and b) no characters follow the variable name that could possibly be interpreted as part of it.
http://php.net/manual/en/language.variables.variable.php
In order to use variable variables with arrays, you have to resolve an
ambiguity problem. That is, if you
write $$a[1] then the parser needs to
know if you meant to use $a[1] as a
variable, or if you wanted $$a as the
variable and then the [1] index from
that variable. The syntax for
resolving this ambiguity is: ${$a[1]}
for the first case and ${$a}[1] for
the second.
The brackets allow you to remove ambiguity for the PHP parser in some special cases.
In your case, they are equivalent.
But consider this one:
$foobar = 'hello';
$foo = 'foo';
echo "${$foo . 'bar'}"; // hello
Without the brackets, you will not get the expected result:
echo "$$foo . 'bar'"; // $foo . 'bar'
For clarity purposes, I would however strongly advise against this syntax.
If you write
echo "This is a test using $vars"
You do not get content of $var in result text.
If you write
echo "This is a test using {$var}s";
Everything will be OK.
P.S. It works only with "" but not for ''.
The {} notation is also useful for embedding multi-dimensional arrays in strings.
e.g.
$array[1][2] = "square";
$text = "This $array[1][2] has two dimensions";
will be parsed as
$text = "This " . $array[1] . "[2] has two dimensions";
and you'll end up with the text
This Array[2] has two dimensions
But if you do
$text = "This {$array[1][2]} has two dimensions";
you end up with the expected
This square has two dimensions.
Given the following:
$foo = "Yo [user Cobb] I heard you like dreams so I put a dream in yo dream in yo dream so you can dream while you dream while you dream."
I'd like to do this:
$foo = bar($foo);
echo $foo;
And get something like this:
Yo Cobb I heard you like dreams so I put a dream in yo dream in yo dream so you can dream while you dream while you dream.
I'm unsure of how the bar function should work. I think this is doable with regular expressions but I personally find those hard to understand. Using the strpos function is another method but I wonder if there is a better solution.
Pseudocode is fine but actual code will be appreciated.
Edit:
These tags are not placeholders as the 2nd part is a variable value.
Edit:
All of the str_replace answers are incorrect as the tags contain variable content.
You could use preg_match_all to search the string for tags.
function bar($foo)
{
$count = preg_match_all("/\[(\w+?)\s(\w+?)\]/", $foo, $matches);
if($count > 0)
{
for($i = 0; $i < $count; $i++)
{
// $matches[0][$i] contains the entire matched string
// $matches[1][$i] contains the first portion (ex: user)
// $matches[2][$i] contains the second portion (ex: Cobb)
switch($matches[1][$i])
{
case 'user':
$replacement = tag_user($matches[2][$i]);
str_replace($matches[0][$i], $replacement, $foo);
break;
}
}
}
}
Now you can add more functionality by adding more cases to the switch.
As the tags contain content you want to parse and are not static to be replaced tags you’ll have to use regular expressions. (It’s the easiest way to go.)
preg_replace() is the regular expression function to replace text.
$pattern = '/\[user (\w+)\]/i';
$rpl = '${1}';
return preg_replace($pattern, $rpl, $foo);
This will match for a [user xy] tag where xy is a word (sequence of word-characters) of at least one character. As it is in parenthesis it is accessible with {1} in the replace-string. $foo is the string you want to parse. Returned is the parsed string with replaced tag. The i modifier on the pattern will make the matching case-insensitive. Remove it if you want it to be case-sensitive.
(The example you gave parses from [user Cobb] to a wikipedia url leonardo dicabrio, which is in no correspondence to neither user nor Cobb. So however you got there, you’ll have to do that (query a db? whatever). If it was just not careful enough providing example code; you probably wanted to point to a static url and add part of the tag content to it, which is what I did here.)
str_replace() is going to be your best option:
function bar($foo) {
$user = 'Cobb';
return str_replace('[user]', $user, $foo);
}
$foo = 'Yo [user] I heard you like dreams so I put a dream in yo dream in yo dream so you can dream while you dream while you dream.'
$foo = bar($foo);
print $foo; // Will print "Yo Cobb I heard you like dreams so I put a dream in yo dream in yo dream so you can dream while you dream while you dream."
What about str_replace?
function bar(foo)
return str_replace($arrayWithStringsToGetReplaced,
$arrayWithStringsToReplaceWith,
$foo)
If I understand the comments below
correctly.
This is obviously beyond me. Moving on... :)
Regular Expressions are the way to go. Hard yes, but the benefit gained from learning them far outweighs the effort needed to learn.
From php.net
<?php
$text = 'The price is PRICE ';
$lookFor = 'PRICE';
$replacement = '$100';
echo $replacement.'<br />';
//will display
//$100
echo str_replace($lookFor, $replacement, $text).'<br />';
//Will display
//The price is $100
?>
I cannot use strtolower as it affects all characters. Should I use some sort of regular expression?
I'm getting a string which is a product code. I want to use this product code as a search key in a different place with the first letter made lowercase.
Try
lcfirst — Make a string's first character lowercase
and for PHP < 5.3 add this into the global scope:
if (!function_exists('lcfirst')) {
function lcfirst($str)
{
$str = is_string($str) ? $str : '';
if(mb_strlen($str) > 0) {
$str[0] = mb_strtolower($str[0]);
}
return $str;
}
}
The advantage of the above over just strolowering where needed is that your PHP code will simply switch to the native function once you upgrade to PHP 5.3.
The function checks whether there actually is a first character in the string and that it is an alphabetic character in the current locale. It is also multibyte aware.
Just do:
$str = "STACK overflow";
$str[0] = strtolower($str[0]); // prints sTACK overflow
And if you are using 5.3 or later, you can do:
$str = lcfirst($str);
Use lcfirst():
<?php
$foo = 'HelloWorld';
$foo = lcfirst($foo); // helloWorld
$bar = 'HELLO WORLD!';
$bar = lcfirst($bar); // hELLO WORLD!
$bar = lcfirst(strtoupper($bar)); // hELLO WORLD!
?>
For a multibyte first letter of a string, none of the previous examples will work.
In that case, you should use:
function mb_lcfirst($string)
{
return mb_strtolower(mb_substr($string, 0, 1)) . mb_substr($string, 1);
}
The ucfirst() function converts the first character of a string to uppercase.
Related functions:
lcfirst() - converts the first character of a string to lowercase
ucwords() - converts the first character of each word in a string to uppercase
strtoupper() - converts a string to uppercase
strtolower() - converts a string to lowercase
PHP version: 4 and later