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