replace string in php if exist - php

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);

Related

Find a string that is not always the same [PHP]

I need help finding something in a variable that isn't always the same, and then put it in another variable.
I know that what I'm looking for has 5 slashes, it starts with steam://joingame/730/ and after the last slash there are 17 numbers.
Edit: It doesn't end with a slash, thats why I need to count 17 numbers after the fifth slash
Assuming what you're looking for looks something like this:
steam://joingame/730/11111111111111/
Then you could use explode() as a simple solution:
$gameId = explode('/', 'steam://joingame/730/11111111111111/');
var_dump($gameId[4]);
or you could use a regex as a more complex solution:
preg_match('|joingame/730/([0-9]+)|', 'steam://joingame/730/11111111111111/', $match);
var_dump($match[1]);
This splits the string into an array then return the last element as the game_id. It doesn't matter how many slashes. It will always return the last one.
$str = 'steam://joingame/730';
$arr = explode("/", $str) ;
$game_id = end($arr);
Following on from what DragonSpirit said
I modified there code so the string can look like
steam://joingame/730/11111111111111
or
steam://joingame/730/11111111111111/
$str = 'steam://joingame/730/11111111111111/';
$rstr = strrev( $str ); // reverses the string so it is now like /1111111111...
if($rstr[0] == "/") // checks if now first (was last ) character is a /
{
$nstr = substr($str, 0, -1); // if so it removes the /
}
else
{
$nstr = $str; // else it dont
}
$arr = explode("/", $nstr) ;
$game_id = end($arr);
Thanks for the help, I've found a solution for the problem. I'm going to post an uncommented version of the code on pastebin, becuase I couldn't get the code saple thing working here.
code

Php regex to get results of 4 strings between slashes

I'm having troubles with regex. I'm trying to isolate query results that are like :
string1/string2/string3/string4
string1/string2/string3/string4/string5
I want to find the first case from the two above, the one with the chain ending after "string4".
I've tryied this regex that doesn't actually works :
$my_regex = "/^(.+)\/(.+)\/(.+)\/(.+)$/";
if (preg_match($my_regex, $category->name)) {
...
}
Am I missing something ?
With a regex, a solution could be :
$my_regex = "/^([^\/]+\/){3}[^\/]+$/";
if (preg_match($my_regex, $category->name)) {
...
}
Don't use a regex, use explode() function
$pieces = explode("/", $your_string); //pieces will be an array
foreach($pieces as $piece) {
[...]
}

preg_match, addslashes,mb_substr not working for long strings

I am parsing an html file. I have a big string which is basically a script.
The string looks likes this:
var spConfig = new
Product.Config({"outofstock":["12663"],"instock":["12654","12655","12656","12657","12658","12659","12660","12661","12662","12664","12665"],"attributes":{"698":{"id":"698","code":"aubade_import_colorcode","label":"Colorcode","options":[{"id":"650","label":"BLUSH","price":"0","products":["12654","12655","12656","12657","12658","12659","12660","12661","12662","12663","12664","12665"]}]},"689":{"id":"689","code":"aubade_import_size_width","label":"Size
Width","options":[{"id":"449","label":"85","price":"0","products":["12654","12657","12660","12663"]},{"id":"450","label":"90","price":"0","products":["12655","12658","12661","12664"]},{"id":"451","label":"95","price":"0","products":["12656","12659","12662","12665"]}]},"702":{"id":"702","code":"aubade_import_size_cup","label":"Size
Cup","options":[{"id":"1501","label":"A","price":"0","products":["12654","12655","12656"]},{"id":"1502","label":"B","price":"0","products":["12657","12658","12659"]},{"id":"1503","label":"C","price":"0","products":["12660","12661","12662"]},{"id":"1504","label":"D","price":"0","products":["12663","12664","12665"]}]}},"template":"\u20ac#{price}","basePrice":"57","oldPrice":"57","productId":"12666","chooseText":"Choose
option...","taxConfig":{"includeTax":true,"showIncludeTax":true,"showBothPrices":false,"defaultTax":19.6,"currentTax":19.6,"inclTaxTitle":"Incl.
Tax"}});
var colorarray = new Array();
colorarray["c650"] = 'blush';
Event.observe('attribute698', 'change', function() {
var colorId = $('attribute698').value;
var attribute = 'attribute698';
var label = colorarray["c"+colorId];
if ($('attribute698').value != '') {
setImages(attribute, colorId, label);
}
}); // var currentColorLabel = 'blush'; // var currentSku = '5010-4-n'; // var currentPosition = 'v'; // //
Event.observe(window, 'load', function() { //
setImages('attribute698', null, currentColorLabel); // });
I need to extract the content from first "(" upto first ";".
I have tried to do string extract and failed.I have tried preg match I have failed.
Kindly tell me some solution to my problem.Below are my tried solution and issues.
$strScript = $tagscript->item(0)->nodeValue;
//this line returns empty string
$str_slashed = addslashes(trim($strScript) );
$pattern = '/\((.*);/';
preg_match($pattern,$str_slashed,$matches);
echo 'matches'."<br />";
var_dump($matches);
//Add slashes works only if I use it before assignment to other string
$matches = array();
$strScript = addslashes ($tagscript->item(0)->nodeValue);//. "<br />";
$pattern = '/\((.*);/';
preg_match($pattern,$strScript,$matches);
echo 'matches'."<br />";
var_dump($matches);
//str extract method
$posBracket = stripos ($strScript,'(');
echo $posBracket."<br />";
$posSemiColon = strpos ($strScript,';');
echo $posSemiColon."<br />";
$temp = mb_substr ($strScript,$posBracket ,($posSemiColon-$posBracket));
echo $temp."<br />";
The above code works for small strings
$strScript = "manisha( [is goo girl] {come(will miss u) \and \"play} ; lets go home;";
but wont work for the long strings.
How can i resolve this issue?Please help me!
You have to add multiline switch to your regular expressions.
Try $pattern = '/\((.*);/s'; or $pattern = '/\((.*);/m';
Try using /\(([^;]*)/ as your pattern. [^;] means any character that is not a ;.
Edit: also turn multiline mode on, as suggested by rogers; therefore the whole pattern should look somewhat like /\(([^;]*)/s.
Edit: you should be aware, that this is not really error-proof. Say, you'll get a ; inside some property of the object of which JSON representation is included in your string.

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;
}

remove double quotes around "function() { ... }"

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); ?>

Categories