Can't replace text in variable with strreplace - php

I have a variable that I echo, like this:
echo "hm={$yes["n"]}";
I need to replace every instance of (whitespace) with +. What I tried was putting this:
str_replace(" ","+",{$yes["n"]});
before I echoed it out.
It said unexepected {, so I tried:
str_replace(" ","+",$yes["n"]);
Where nothing happened.

You have forgotten to assign the output of str_replace to the variable.
$yes["n"] = 'string with whitespace';
$yes["n"] = str_replace(" ","+",$yes["n"]);
echo "hm={$yes["n"]}"; // echoes hm=string+with+whitespace

Related

eval() function in php

here is a code where I don't understand why the php code where the output is: This is a $string with my $name in it. This is a cup with my coffee in it.
<?php
$string = 'cup';
$name = 'coffee';
$str = 'This is a $string with my $name in it.';
// will not echo the value of the strings variable because there in ' '
echo $str. "\n";
// this function is like writing the php code outside of it
// it gets a string with php statments (;)
// because the code is written in a string
// if it is written it double quotes you have to escape $ and "
// and if it is written in single quotes you have to escape '
eval("\$str = \"$str\";");
//it is not like this, why?????
//eval('$str = "$str";');
// and not like this, why???????
//$str = "$str" ;
echo $str. "\n";
?>
why doesn't the statement : eval('$str = "$str";'); or the statement: $str = "$str" ; do the same thing as the statement: eval("\$str = \"$str\";"); in this code
A Double quoted string evaluates all the variables inside it. A Single Quoted String does not.
Now to this statement
eval("\$str = \"$str\";");
first \$str -> the $ is escaped, so its a literal, and not the $str variable
second $str -> the $ is not escaped and the whole string is in double quotes, so this will become
$str = "This is a $string with my $name in it."
Now this PHP code is evaluated, which assigns the string on right to the variable on left. Hence $str becomes what This is a cup with my coffee in it.
Eval should be avoided.
//it is not like this, why?????
//eval('$str = "$str";');
Because the input string might contain single quotes, so you can't use them to start and end the string.
// and not like this, why???????
//$str = "$str" ;
Because you want to evaluate a string, and the above is no string.
I don't see the point of this example, just use double quotes:
<?php
$string = 'cup';
$name = 'coffee';
$str = "This is a $string with my $name in it.";
echo $str. "\n";
?>
In the first eval statement:
eval("\$str = \"$str\";");
As second $ is not escaped, and you are using double quotes over the entire arguement, so second $str's value is passed to the eval, and the argument of eval becomes:
eval("\$str = \"This is a $string with my $name in it.\";");
which when evaluated, becomes:
$str = "This is a $string with my $name in it.";
Which assigns 'This is a cup with my coffee in it.' to $str.
In the second eval:
eval('$str = "$str";');
the statement evaluated is:
$str = "$str";
Which is same as your third statement. When this statement is executed, it converts non-strings to strings. In this case, $str is already a string, so this statement has no effect on the value of $str.
Hope this helps. :)
Why would you need eval in this context ?
Variables inside single quotes will not be interpreted , Instead put it under double quotes.
$str = "This is a $string with my $name in it."; //<--- Replaced single quotes to double quotes.
Secondly.. If you are really worried about escaping why don't you make use of a HEREDOC Syntax
<?php
$string = 'cup';
$name = 'coffee';
$cont=<<<ANYCONTENT
This is a $string with my $name in it. This text can contain single quotes like this ' and also double quotes " too.
ANYCONTENT;
echo $cont;
OUTPUT :
This is a cup with my coffee in it. This text can contain single quotes like this ' and also double quotes " too.

How to avoid printing variable in doublequote string

Code snippet:
$str = "text";
echo "str variable contains $str";
This code returns:
str variable contains text
How to return following string without closing whole echo in singlequotes? I want to somehow esape variable still using doublequotes, like this:
str variable contains $str
echo "str variable contains \$str";
If you want to automate this, use str_replace().
$str = "text";
$text = "str variable contains $str";
$text = str_replace('$', '\$', $text);
echo $text;

Using explode on a variable that doesn't have quotes

I have a line that grabs data from a web database, outputting this:
KJFK 180451Z 23007KT 10SM CLR 27/22 A3008 RMK AO2 SLP184 T02670222 403500261
(note, this string changes per hour on a dynamic basis).
That string up there has more information that I want displayed in the end. Let's say I want to display just the 23007KT.
I was thinking of doing $elements = explode(" ", $metar);
Note: $metar was previously defined as the action that gets that long string.
<td><?php $a = $ad[icao]; $metar = get_metar(strtoupper($a)); ?> </td>
I think the issue is that I need to add quotes to the beginning of the long string. I have tried putting one of these strings, with the quotes, and it works, but that will only be useful for an hour (because it will change after that time)
I have also tried doing $elements = explode(" ", "$metar"); but no success.
How do I go about adding in the quotes to the beginning of that string?
Thanks.
Try this and it works for me,
$metar='KJFK 180451Z 23007KT 10SM CLR 27/22 A3008 RMK AO2 SLP184 T02670222 403500261';
$elements = explode(" ", $metar);
//print_r($elements);
echo $elements[2];//outputs 23007KT
After using the $elements = explode(" ", $metar); you will get an array in the $elements variable.
You need to check that it comes correct or not to do that use this code print_r($elements);
And as you told that you need 23007KT from string that will 3rd element.
so use the below code
echo $elements['2'];
and you will get this value.

PHP, explode multiple words and prefix them with a character [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Add a prefix to each item of a PHP array
I try to use Boolean mode full text search.
If a user types more than two words, it supposes to make like this.
Search Keyword : Apple Macbook Air
Result : +Apple +Macbook +Air
So, I made a php command to make this happen, but didn't work.
$ArrayKeywords = explode(" ", $b_keyword);
for($i = 0; $i < sizeof($ArrayKeywords); $i++)
$array_keyword = '+"$ArrayKeywords[$i]" ';
can you tell me how to make this happen?
Can also do (demo)
echo preg_replace('(\w+)', '+$0', 'Apple Macbook Air');
Why not just do this:
$keyword = '+' . trim(str_replace(' ',' +',$b_keyword));
Don't really need to for loop there
// trims off consecutive spaces in the search term
$b_keyword = preg_replace('/\s+/', ' ', $b_keyword);
$ArrayKeywords = explode(" ", $b_keyword);
echo '+' . implode(' +', $ArrayKeywords);
I see there's a bit of a misunderstanding how variables inside strings work.
You may have learned that anything inside single quotes is parsed as is and inside double quotes the variables' contents are printed, like so:
$foo = 'bar';
echo 'foo: $foo'; // result: foo: $foo
echo "foo: $foo"; // result: foo: bar
But, you can't combine the two methods; putting double quotes inside single quotes doesn't make the variable's contents printed. The double quotes work only if the entire string is delimited by them. Therefore the following won't work:
echo 'foo: "$foo"'; // result: foo: "$foo"
Expanding this to your case, you can just replace the single quotes with double quotes and drop the inner double quotes.
$array_keyword .= "+$ArrayKeywords[$i] ";
Also note that you have to concatenate the new words into the variable (.=), otherwise the variable is overwritten on each loop.
Side note: it's much easier to use a foreach loop than a for loop when looping through arrays:
$ArrayKeywords = explode(" ", $b_keyword);
$array_keyword = '';
foreach( $ArrayKeywords as $keyword ) {
$array_keyword .= '+$keyword ";
}
If you want it for tabs, newlines, spaces, etc.
echo preg_replace('(\s+)', '$0+', ' Apple Macbook Air');
//output: +Apple +Macbook +Air

preg_replace removes second backslash at start of line

Consider this:
$sServerPath = "\\\\nlyehvedw1cl016\\projects$\\ARCLE_SW_SVN\\";
$sSVNParentPath = $sServerPath."svn\\";
$bla = "
authz_module_name = TEST_TestRepos
repository_dir = bla
W";
$sSVNParentPath = $sServerPath."svn\\";
$sReplaceBy = "repository_dir = ".$sSVNParentPath.$sProjectName."\n";
echo $sReplaceBy;
echo preg_replace ('/repository_dir = ([a-zA-Z0-9\/].*?)\n/i', $sReplaceBy, $bla);
The result is:
repository_dir = \\nlyehvedw1cl016\projects$\ARCLE_SW_SVN\svn\
authz_module_name = TEST_TestRepos
repository_dir = \nlyehvedw1cl016\projects$\ARCLE_SW_SVN\svn\
W
The echo of $sReplaceBy shows the resulting string as I expect it, including the first 2 back-slashes.
However, after the preg_replace, the echo of the result shows only one back-slash!
Anybody know what's causing this?
From PHP docs:
To use backslash in replacement, it must be doubled ("\\" PHP string).
Since your replacement doesn't contain quotes, you can simply use addslashes():
echo preg_replace ('/repository_dir = ([a-zA-Z0-9\/].*?)\n/i', addslashes($sReplaceBy), $bla);

Categories