remove double quotes around "function() { ... }" - php
Brain not working today - can anyone give me a regexp that would turn:
{events:{click:"function() { alert('hi'); }"}}}}}
into:
{events:{click:function() { alert('hi'); }}}}}}
any any other instances such as this in a string.
if this helps expand my question:
So far using this:
$replacement = '${1}:';
$json_options = preg_replace('/"(\w+)"\s*:/', $replacement, $json_options);
I have it turn this:
string(1051) "{"chart":{"renderTo":"tx_count","defaultSeriesType":"spline"},"credits":{"enabled":false},"series":[{"type":"spline","name":"Transactions Per Day","color":"#4572A7","data":[3,5,3,3,3,6,6,92,2]},{"type":"spline","name":"Value Per Day","yAxis":1,"color":"#89A54E","data":[30,232,172.99,30,160,550,596,2407.96,20]},{"type":"spline","name":"Average Value Per Day","yAxis":2,"color":"#AA4643","data":[10,46.4,57.7,10,53.3,91.7,99.3,26.2,10]}],"legend":{"enabled":true},"xAxis":{"labels":{"rotation":"-45"},"categories":["02\/02\/2011","03\/02\/2011","06\/02\/2011","07\/02\/2011","08\/02\/2011","09\/02\/2011","10\/02\/2011","11\/02\/2011","14\/02\/2011"]},"title":{"text":"Transactions Summary","align":"center","x":0,"y":20},"yAxis":[{"title":{"text":"Transactions","style":{"color":"#4572A7"}}},{"title":{"text":"Value","style":{"color":"#89A54E"}},"opposite":true},{"title":{"text":"Value (Average)","style":{"color":"#AA4643"}},"opposite":true}],"plotOptions":{"series":{"cursor":"pointer","point":{"events":{"click":"function() { alert('hi'); }"}}}}}"
into this (which is perfect),
string(947) "{chart:{renderTo:"tx_count",defaultSeriesType:"spline"},credits:{enabled:false},series:[{type:"spline",name:"Transactions Per Day",color:"#4572A7",data:[3,5,3,3,3,6,6,92,2]},{type:"spline",name:"Value Per Day",yAxis:1,color:"#89A54E",data:[30,232,172.99,30,160,550,596,2407.96,20]},{type:"spline",name:"Average Value Per Day",yAxis:2,color:"#AA4643",data:[10,46.4,57.7,10,53.3,91.7,99.3,26.2,10]}],legend:{enabled:true},xAxis:{labels:{rotation:"-45"},categories:["02\/02\/2011","03\/02\/2011","06\/02\/2011","07\/02\/2011","08\/02\/2011","09\/02\/2011","10\/02\/2011","11\/02\/2011","14\/02\/2011"]},title:{text:"Transactions Summary",align:"center",x:0,y:20},yAxis:[{title:{text:"Transactions",style:{color:"#4572A7"}}},{title:{text:"Value",style:{color:"#89A54E"}},opposite:true},{title:{text:"Value (Average)",style:{color:"#AA4643"}},opposite:true}],plotOptions:{series:{cursor:"pointer",point:{events:{click:"function() { alert('hi'); }"}}}}}"
now i need to remove double quotes round any function() { ... stuff... } that may be in the string.
You can $string = str_replace('"', "", $string);, no need for a regexp in this particular example.
Or try this then:
$string = str_replace(array('"function()','}"}'), array('function()', '}}'), $string);
This works for me:
<?php preg_replace('/"(function\s*?\(\)\s*?{.*?})"/', "$1", $string); ?>
Related
Changing normal quotes to curly ones in 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
Regex : Removing all extra whitespace, line-breaks, and empty spaces
Update: It seems like it is just a regex problem. I am trying to remove all extra whitespace, line-breaks, and empty spaces from user story with a function to grab only 100 characters Issue is although 100 character limit works, the removing of whitespace, linebreaks and empty spaces does not apply: function aboutme_echo($x, $length) { if(strlen($x) <= $length) { echo $x; } else { $y = substr($x,0,$length) . '...'; echo $y; } } aboutme_echo((preg_replace("/\s+/"," ", $aboutme)), 100); Example String: 🤣🤣🤣WHAT?! That's crazy! Long story short, 😛😛someone reached out to me who had a pharma virus. 😎I have the opportunity to rebuild their site, but I can't rush the planning and staging, but i...
Something like this maybe? function cleanExcerpt($string) { $pattern = '/\s+/'; $replace = ' '; $cleanstring = trim(preg_replace($pattern,$replace,$string)); return strtok(wordwrap($cleanstring, 100, "...\n"), "\n"); } To use, you must pass through a string and echo the function like this: $string = "Example String: 🤣🤣🤣WHAT?! That's crazy! Long story short, 😛😛someone reached "; echo cleanExcerpt($string);
replace string in php if exist
I have a string in php that looks like this $(window).load(function(){ $('.someclass').click(function () { $(this).text("clicked"); }); }); what i want is - if string contains $(window).load(function(){ then replace this and also the end braces }); with empty string "" But if $(window).load(function(){ do not exist then do nothing. Here is what i have tried: if(strpos($str,"$(window).load(function(){") == -1){ // do nothing } else{ str_replace("$(window).load(function(){","",$str); // how do i replace the last }); with "" }
If your code is nicely indented like that, this might just work for you: $str = <<<EOM $(window).load(function(){ $('.someclass').click(function () { $(this).text("clicked"); }); }); EOM; $start = preg_quote('$(window).load(function(){'); $end = preg_quote('});'); $new = preg_replace("/^$start\s*(.*?)^$end/ms", '$1', $str); print_r($new);
You will need regular expressions for this one if you can guarantee that the }); will be the last one. If so: $str = preg_replace("#\$\(window\)\.load\(function\(\) \{(.*)\}\);#is","",trim($str)); Should do the trick. If you cannot guarantee that the }); you want to replace will be the last occurence, you will have to walk through your code and count the braces. No other way, sadly :-(
$str = substr($str, 0, strlen($str) - 4); This will remove the last 3 characters of the string.
Find the position of the last occurrence with strrpos ? Then maybe do a str_replace from that point with a limit of 1? You should check the modified string with an external call to something like JSlint to make sure you didnt create malformed code.
I think, a working way will be just to test for (window).load, and to add this : str_replace('$(window).load', "var functionOnLoad = ", $str); Don't forget to add a call to this function if you want it to be execute. Somethink like : str_replace('</script>', "functionOnLoad();</script>", $str);
Content Spinning using PHP?
Can anyone please help me? Say if I had this text or a smaller section stored in a variable, how can I randomise the words in the '{ }' ? For example, the first one is "{important|essential|crucial|critical|vital|significant}" how can I make PHP choose one of those words randomly and then echo it? Thanks for helping me. :)
http://webarto.com/62/random-sentence-spinning-function function get_random($matches) { $rand = array_rand($split = explode("|", $matches[1])); return $split[$rand]; } function show_randomized($str) { $new_str = preg_replace_callback('/\{([^{}]*)\}/im', "get_random", $str); if ($new_str !== $str) $str = show_randomized($new_str); return $str; } Applied on your text file... http://ideone.com/rkuf6
strip off initial and ending curly braces, you can use trim() explode the resulting string on | using explode() use array_rand() for the array you had in last step
Will not work with nested({a|x {b|c} y|z})! function doStuff($from){ $to=""; while(($pos=strpos($from,'{'))!==false){ $to.=substr($from,0,$pos); $from=substr($from,$pos); $closepos=strpos($from,'}'); $arr=explode('|',substr($from,1,$closepos-1)); $to.=$arr[array_rand($arr)]; $from=substr($from,$closepos+1); } return $to.$from; }
How to convert a string with numbers and spaces into an int
I have a small problem. I am tryng to convert a string like "1 234" to a number:1234 I cant't get there. The string is scraped fro a website. It is possible not to be a space there? Because I've tried methods like str_replace and preg_split for space and nothing. Also (int)$abc takes only the first digit(1). If anyone has an ideea, I'd be greatefull! Thank you!
This is how I would handle it... <?php $string = "Here! is some text, and numbers 12 345, and symbols !£$%^&"; $new_string = preg_replace("/[^0-9]/", "", $string); echo $new_string // Returns 12345 ?>
intval(preg_replace('/[^0-9]/', '', $input))
Scraping websites always requires specific code, you know how you receive the input - and you write code that is required to make it usable. That is why first answer is still str_replace. $iInt = (int)str_replace(array(" ", ".", ","), "", $iInt);
$str = "1 234"; $int = intval(str_replace(' ', '', $str)); //1234
I've just came into the same issue, however the answer that was provided wasn't covering all the different cases I had... So I made this function (the idea popped in my mind thanks to Dan) : function customCastStringToNumber($stringContainingNumbers, $decimalSeparator = ".", $thousandsSeparator = " "){ $numericValues = $matches = $result = array(); $regExp = null; $decimalSeparator = preg_quote($decimalSeparator); $regExp = "/[^0-9$decimalSeparator]/"; preg_match_all("/[0-9]([0-9$thousandsSeparator]*)[0-9]($decimalSeparator)?([0-9]*)/", $stringContainingNumbers, $matches); if(!empty($matches)) $matches = $matches[0]; foreach($matches as $match): $numericValues[] = (float)str_replace(",", ".", preg_replace($regExp, "", $match)); endforeach; $result = $numericValues; if(count($numericValues) === 1) $result = $numericValues[0]; return $result; } So, basically, this function extracts all the numbers contained inside of a string, no matter how many text there is, identifies the decimal separator and returns every extracted number as a float. One can specify what decimal separator is used in one's country with the $decimalSeparator parameter.
Use this code for removing any other characters like .,:"'\/, !##$%^&*(), a-z, A-Z : $string = "This string involves numbers like 12 3435 and 12.356 and other symbols like !## then the output will be just an integer number!"; $output = intval(preg_replace('/[^0-9]/', '', $string)); var_dump($output);