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;
Related
I'm trying to change straight quotes ("something") to curly quotes („something“) in PHP. Other answers are not for my situation, since I have a product details imported from DB as variable, using str_replace I've managed to only change it to „ and it seems like I can't change the second one to be “. From what I know, there is no way to accomplish this.
For example:
$description outputs -> Hello "everyone", I would like to "change" this straight "quotes" to "curly" ones.
What I would like:
$description outputs -> Hello „everyone“, I would like to „change“ this straight „quotes“ to „curly“ ones.
Try using preg_replace with the pattern "(.*?)". Then, replace with the capture group $1 inside curly quotes.
$input = "Hello \"everyone\", I would like to \"change\" this straight \"quotes\" to \"curly\" ones.";
$output = preg_replace("/\"(.*?)\"/", "„$1“", $input);
echo $output;
This prints:
Hello „everyone“, I would like to „change“ this straight „quotes“ to „curly“ ones.
Edit:
You are trying to replace HTML code, where double quotes have been encoded, so try the following:
$input = "Exklusiv von buttinette: Baumwollstoff "Leo",";
$output = preg_replace("/"(.*?)"/", "“$1”", $input);
echo $output;
This prints:
Exklusiv von buttinette: Baumwollstoff “Leo”,
Using explode and array_reduce:
$str = 'Hello "everyone", I would like to "change" this straight "quotes" to "curly" ones.';
$parts = explode('"', $str); // or explode('"', $str);
$carry = array_shift($parts);
$result = array_reduce($parts, function ($c,$i) {
static $up = false;
return $c . ((true === $up=!$up) ? '„' : '“') . $i;
}, $carry) ;
demo
Obviously if your original quotes are html entities you have to change the first parameter of explode.
Using strtok:
$str = 'Hello "everyone", I would like to "change" this straight "quotes" to "curly" ones.';
$result = substr(strtok(".$str", '"'), 1);
while (false !== $part = strtok('"')) {
$result .= "„${part}“" . strtok('"');
}
demo
I am getting data from a page like this:
<?php $speaker = $page->uri();
$speakerEvents = page('program')->grandchildren()->filter(function($child) use($speaker) {
$speakers = $child->speaker()->toStructure();
return $speakers->findBy('selectspeaker', $speaker);
});
echo $speakerEvents;
?>
It's output is:
"page/page/pageIWant
page/page/pageIWant"
The Result I want is
pageIWant
pageIWant
I tried to get the last name with
echo basename($speakerEvents);
But I only get one of the last pageIWant
How do I get the last pages without removing the first URL?
Use the explode method to get array of URL
<?php
$link = $_SERVER['PHP_SELF'];
$link_array = explode('/',$link);
echo $page = end($link_array);
?>
If your output is
page/page/pageIWant
page/page/pageIWant
<?php
$text = "page/page/pageIWant";
$text_arr = explode('/',$text);
echo $page = end($text_arr);
// this will print: pageIWant
?>
Your string has a line break as path separator. You need to split lines by either \r\n (CR-LF), \n, or \r which can be done with preg_split. If you can ensure one of the formats, you can also use the simple explode function.
foreach (preg_split('~(?:\r?\n|\r)~u', $speakerEvents) as $path)
echo basename($path) , PHP_EOL;
As AbraCadaver noted, you can add the flag PREG_SPLIT_NO_EMPTY to preg_split if you do not want empty lines to be handled.
If the double qoutes you show in the question are part of the string, you need further more to trim the string:
foreach (preg_split('~(?:\r?\n|\r)~u', trim($speakerEvents, '"')) as $path)
echo basename($path) , PHP_EOL;
You can explode the string e.g.
$array = explode('/', 'page/page/pageIWant');
Then you can retrieve it using the index like so:
$array[(count($array) - 1)];
I have a doubt, it may be something simple but I have no knowledge to solve it.
I get a string in php
$ string = "[link = someUrl] Text [link]"
And I would like to turn this string into:
"<a href='someUrl'> Text <a/>"
How do I change the URL? and How Can I do the opposite?
Remember that the string belongs to a text with more strings of these gifts.
Short preg_replace solution:
$s = "[link=someUrl] Text [/link]";
$result = preg_replace('#\[[^=]+=([^]]+)\]([^[]+).*#', '<a href=\'$1\'>$2</a>', $s);
print_r($result);
The output (as web page source code):
<a href='someUrl'> Text </a>
You can use the following code
function transformText($string) {
preg_match("/\[link\=([^\]]*)\](.*?)\[\/link]/", $string, $matches);
$someUrl = $matches[1];
$text = $matches[2];
$newString = "<a href='$someUrl'>$text</a>";
return $newString;
}
$string = "[link=someUrl] Text [/link]"; // Test string
echo (transformText($string));
Live demo for the regex used : https://regex101.com/r/tzVfmH/4
Note : The above code works only if there's a single [link], [/link] pair.
If multiple occurrences are to be handled then its better to use regex search and replace, using php's preg_replace as suggested in RomanPerekhrest's answer.
I want to replace all image contained in a string, which is like:
<img src="data:image/png;base64,IMAGE DATA
with a reference to a cid.
Since the images can't get the same cid's, i need to replace them with an increment. But i don't know how to. Only thing i've found so far is following code, which replaces the string with the same:
$string = 'normal text [everythingheregone] after text ';
$pattern = '\[.*?]';
$replacement = '[test]'
echo preg_replace($pattern, $replacement, $string);
//normal text [test] after text
Do you have any ideas?
Shame on me, i should've searched a little bit more:
Here is what i've found out on replacing with increment:
$count = 0;
preg_replace_callback('/test/', 'rep_count', $content);
function rep_count($matches) {
global $count;
return 'test' . $count++;
}
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.