Changing normal quotes to curly ones in php - php

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

Related

Remove quotes from string inside of array

I have a string that looks like this:
$string = '"excludeIF":["miniTrack","isTriangleHanger","tubeTrack","boxTrack"]';
I need to get rid of the " that are inside of the [] array so it looks like this:
$string = '"excludeIF":[miniTrack, tubeTrack, boxTrack]';
I was trying some regex but I kept getting rid of all of the quotes.
For this particular example:
$string = '"excludeIF":["miniTrack","isTriangleHanger","tubeTrack","boxTrack"]';
preg_match("/((?<=\[).*(?=\]))/", $string, $match);
$change = str_replace('"', "", $match[0]);
$result = preg_replace("/$match[0]/", $change, $string);
What this does is it gets the content inside the square brackets, removes the quotes, then replaces the original content with the cleaned content.
This may run into errors if you have the exact same string outside of square brackets later on, but it should be an easy fix if you understand what I've written.
Hope it helps.
PS. It would also help if you showed us what regexes you were trying, as you were, perhaps, on the right path but just had some misunderstandings.
So yeah I agree with the comment about the XY Problem, but I would still like to try help.
$string = '"excludeIF":["miniTrack","isTriangleHanger","tubeTrack","boxTrack"]';
You will now need to find the start and end positions of the string that you want edited. This can be done by the following:
$stringPosition1 = strpos($string,'[');
$stringPosition2 = strpos($string,']');
Now you have the correct positions you are able to do a substr() to find the exact string you want edited.
$str = substr($string,$stringPosition1,$stringPosition2);
From here you can do a simple str_replace()
$replacedString = str_replace('"','',$str);
$result = '"excludeIF":' . $replacedString;
It is an excellent idea to look at the PHP docs if you struggle to understand any of the above functions. I truly believe that you are only as good at coding as your knowledge of the language is. So please have a read of the following documents:
Str_pos: http://php.net/manual/en/function.strpos.php
Sub_str: http://php.net/manual/en/function.substr.php
Str_replace: http://php.net/manual/en/function.str-replace.php
test this code:
<?php
$string = '"excludeIF":["miniTrack","isTriangleHanger","tubeTrack","boxTrack"]';
$str_array = str_split($string);
$string_new = '';
$id = 0;
foreach ($str_array as $value) {
if($value == '[' || $id != 0){
$id = ($value != ']') ? 1 : 0;
$string_new .= ($value != "\"") ? $value : '' ;
} else {
$string_new .= $value;
}
}
echo $string_new;
//RESULT "excludeIF":[miniTrack,isTriangleHanger,tubeTrack,boxTrack]
?>
Good luck!
EDIT
<?php
$string = '"excludeIF":["miniTrack","isTriangleHanger","tubeTrack","boxTrack"]';
$part = str_replace("\"","",(strstr($string,'[')));
$string = substr($string,0,strpos($string,'[')).$part;
echo $string;
?>
Other possible solution.
Fun with code!

PHP function that convert 'a,b' to ' "a","b" ' [duplicate]

This question already has answers here:
Add quotation marks to comma delimited string in PHP
(5 answers)
Closed 1 year ago.
I have a variable with string value of 'laptop,Bag' and I want it to look like ' "laptop","Bag" 'or "laptop","Bag". How could I do this one? Is there any php function that could get this job done? Any help please.
This would work. It first, explodes the string into an array. And then implodes it with speech marks & finishes up by adding the opening & closing speech mark.
$string = "laptop,bag";
$explode = explode(",", $string);
$implode = '"'.implode('","', $explode).'"';
echo $implode;
Output:
"laptop","bag"
That's what str_replace is for:
$result = '"'.str_replace(',', '","', $str).'"';
This would be very easy to do.
$string = 'laptop,bag';
$items = explode(',', $string);
$newString = '"'.implode('","', $items).'"';
That should turn 'laptop,bag' into "laptop","bag".
Wrapping that in a function would be as simple as this:
function changeString($string) {
$items = explode(',', $string);
$newString = '"'.implode('","', $items).'"';
return $newString;
}
I think you can explode your string as array and loop throw it creating your new string
function create_string($string)
{
$string_array = explode(",", $string);
$new_string = '';
foreach($string_array as $str)
{
$new_string .= '"'.$str.'",';
}
$new_string = substr($new_string,-1);
return $new_string;
}
Now you simply pass your string the function
$string = 'laptop,Bag';
echo create_string($string);
//output "laptop","Bag"
For your specific example, this code would do the trick:
<?php
$string = 'laptop,bag';
$new_string = ' "' . str_replace(',', '","', $string) . '" ';
// $new_string: "laptop","bag"
?>
That code would also work if you had more items in that list, as long as they are comma-separated.
Use preg_replace():
$input_lines="laptop,bag";
echo preg_replace("/(\w+)/", '"$1"', $input_lines);
Output:
'"laptop","Bag"'
I think you can perform that using explode in php converting that string in to an array.
$tags = "laptop,bag";
$tagsArray = explode(",", $tags);
echo $tagsArray[0]; // laptop
echo $tagsArray[1]; // bag
Reference
http://us2.php.net/manual/en/function.explode.php
related post take a look maybe could solve your problem.
How can I split a comma delimited string into an array in PHP?

list of all PHP preg_replace characters to escape

Where can find a list of all characters that must be escaped when using preg_replace. I listed what I think are three of them in the array $ESCAPE_CHARS. What other ones am I missing.
I need this because I am going to be doing a preg replace on a form submission.
So ie.
$ESCAPE_CHARS = array("#", "^", "[");
foreach ($ESCAPE_CHARS as $char) {
$_POST{"string"} = str_replace("$char", "\\$char", $_POST{"string"});
}
$string = $_POST{"string"};
$test = "string of text";
$test = preg_replace("$string", "<b>$string</b>", $test);
Thanks!
You can use preg_quote():
$keywords = '$40 for a g3/400';
$keywords = preg_quote($keywords, '/');
print $keywords;
// \$40 for a g3\/400

Replace quotes in a string with a HTML tag

I have the following string stored in a variable in PHP.
The words inside the quotes should be in '''bold'''. Like '''this''' and '''that'''
Here triple quotes ''' are used to represent that the word should be shown bold.
What is the most efficient way to replace this with the <strong> tag?
i would say regex with something like that :
$new_string = preg_replace('/\'\'\'([^\']+)\'\'\'/', '<strong>$1</strong>', $string);
Even though #atrepp's answer is correct, I ended up using the following function
function makeBold($string) {
$quote = ''''';
$count = substr_count($string, $quote);
for ($i = 0; $i <= $count/2; $i++) {
$string = preg_replace("/$quote/", '<strong>', $string, 1);
$string = preg_replace("/$quote/", '</strong>', $string, 1);
}
return $string;
}
because
My string was actually in encoded form (ie) it had ' instead of '
His answer doesn't work when the word to be bolded has ' in it

php - Replacing content inside double quotes, including double quotes

So I decided to have a stab at making a text highlighting system. At the moment, I'm just using str_replace to replace a word (e.g. $rstr = str_replace("Console", "<c>Console</c>", $str where $str is the input string.
Something that stumped me was how to replace content inside of speech marks (") and quotes ('). For example, if the string "Console" turned into Console.WriteLine("Words");, how would I replace "Words" with <sr>"Words"</sr> (<sr> is defined in an external stylesheet)?
I had a though that I could use regex, but 1. I don't know how to write regex, and 2. I don't know how to use regex with str_replace.
My workaround solution:
function hlStr($original)
{
$rstr = explode('"', $original);
return $rstr[0].'<sr>"'.$rstr[1].'"</sr>'.$rstr[2];
}
In light of comments below, I think this will be a better resource for you: http://www.regular-expressions.info/
In order to find "anything can go here" you should use regular expressions. This is what they were made for. A regular expression for that might look something like the answers in this question:
How can I match a quote-delimited string with a regex?
then you would use the function preg_replace() like this:
$return_value = preg_replace('/"[^"]+"/', 'replacement text', $str)
leaving this here anyway:
just escape the content with a backslash:
$rstr = str_replace("Console", "Console.WriteLine(\"$variable\");", $str)
this is mostly useful if you are using variables inside your strings. If it is just a straight text replacement, use single quotes:
$rstr = str_replace("Console", 'Console.WriteLine("Words");', $str)
the single quotes count everything but single quotes as just a character.
This is my solution. Explode the whole string by ( " ) symbols, and then run a specific code to each second of them. This code does automatic do it to every second value after " item, which means, if you does : hej " lol ; it would change to : hi <sr>" lol "</sr> ; or if you do : hi " with " you ; it would change to : hi <sr>" with "</sr> you ; etc.
function wrapInside($text,$symbol)
{
$string = explode($symbol, $text);
$i = 1;
$QS = '';
foreach( $queryString as $V )
{
( $i == 1 ) ? ( $QS .= $V ) : ( $QS .= '<sr>"'.trim($V).'"</sr>' );
( $i == 1 ) ? ( $i = 0 ) : ( $i = 1 );
}
$queryString = trim($QS);
return $queryString;
}

Categories