November 6, 2012

How to dynamically create a string in PHP?

Question by All

I have a predefined pattern for building a string, which should be created regularly throughout the script.

$str="$first - $second @@ $third"; // pattern for building the string
$first="word1";
$second="word2";
$third="word3";
$string= ..?? // string should be built here based on the pattern

Currently, I am using eval to generate the string in place based on the pattern originally defined. However, as this happens occasionally and eval is generally bad, I wish to find another method.

NOTE that the pattern is defined only one time above all codes, and I can edit the pattern of all the script by one line only. Thus, what makes $string should not be touched for any change.

I tried create_function, but needs the same number of arguments. With eval, I can easily change the pattern, but with create-function, I need to change the entire script. For example, if changing the string pattern to

$str="$first @@ $second"; // One arg/var is dropped

eval Example:

$str="$first - $second @@ $third"; // Pattern is defined one-time before codes
$first="word1";
$second="word2";
$third="word3";
eval("$string = "$str";");

create_function Example:

$str=create_function('$first,$second,$third', 'return "$first - $second @@ $third";');
$string=$str($first,$second,$third);

Answer by Vulcan

You can use the string formatting capabilities offered by sprintf or vsprintf.

$format = "%s - %s @@ %s"; // pattern for building the string
$first = "word1";
$second = "word2";
$third = "word3";
$string = sprintf($format, $first, $second, $third);

You can use vsprintf if you wish to pass an array.

$format = "%s - %s @@ %s"; // pattern for building the string
$values = array($first, $second, $third);
$string = vsprintf($format, $values);

Answer by Starx

Seems to be rather simple thing to me. Use str_replace() and replace based on patterns

$str="$first$ - $second$ @@ $third$"; // pattern for building the string
$first="word1";
$second="word2";
$third="word3";

$newstr = str_replace('$first$', $first, $str);
$newstr = str_replace('$second$', $second, $newstr);
$newstr = str_replace('$third$', $third, $newstr);
May 14, 2012

Using a variable inside an included file from function

Question by Djave

I’d like to have a header.php file throughout my site. I currently have the following:

header.php

<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="<?php if(isset($depth)){echo $depth;};?>css/style.css">

functions.php

function include_layout_template($template="", $depth="")
{
    global $depth;
    include(SITE_ROOT.DS.'public'.DS.'layouts'.DS.$template);
}

index.php

<?php include_layout_template('header.php', "../"); ?>

But $depth dissappears, I can’t even echo $depth; its just blank. How can I get the depth variable for use in header.php?

Answer by Sergey

You have to rename depth variable in function call

function include_layout_template($template="", $my_depth="")
{
   global $depth;
   //if need $depth = $mydepth

Answer by Starx

Your $depth variable is disappearing, because it is passed as parameter first but then defined to use the global parameter.

I will explain with an example:

$global = "../../"; //the variable outside
function include_layout_template($template="", $depth="")
{
    global $depth; //This will NEVER be the parameter passed to the function
    include(SITE_ROOT.DS.'public'.DS.'layouts'.DS.$template);
}
include_layout_template("header.php", "../");

To solve, simply modify the function parameter other than the depth itself.

function include_layout_template($template="", $cDepth="") { }
May 5, 2012

taking variables from one function to use in another function

Question by Paddy Hallihan

i’m creating a game in javascript for college and i have a button to call a function but i need it to include variables from another function

if i put the function inside the other function where the variables are the button doesn’t call it

is there a way of doing this or to get the variables that were created in the first function and use them in the second function

it is a simple maths game where you get a random number a random sum and another random number
(i.e. 5+7, 4*3, 2/6, etc,)

so i’ve got a function to show the random number using

var ranNum1a=Math.floor(Math.random()*10);

i need the other function to check the users answer but i need to know what the random number was from the other function

Answer by Starx

For simplest case, passing variables to another function might be the best approach to this problem.

Here is an illustration:

fucntion f1(var1, var2) {
    //do you stuff then pass the variable to another function
    f2(var1, var2);
}

function f2(v1, v2) {
    // here v1 will get the value from var1 and v2 from var2 if passed from within the function f1
}
April 29, 2012

PHP – Summary of article

Question by user1257255

I’m working on news script and I would like to create summary function to get little of text from full text content. The function would get 200 characters of full text and then it would search for last space of these 200 characters. The function must also ignore any html or other code and show only first 200 characters of full text content.

Which function is the best for my problem and how to do that function?

Answer by mazzucci

Checkout this helper function from the CodeIgniter framework:

/**
* Character Limiter
*
* Limits the string based on the character count.  Preserves complete words
* so the character count may not be exactly as specified.
*
* @access   public
* @param    string
* @param    integer
* @param    string  the end character. Usually an ellipsis
* @return   string
*/

function character_limiter($str, $n = 500, $end_char = '&#8230;')
{
    if (strlen($str) < $n)
    {
        return $str;
    }

    $str = preg_replace("/s+/", ' ', str_replace(array("rn", "r", "n"), ' ', $str));

    if (strlen($str) <= $n)
    {
        return $str;
    }

    $out = "";
    foreach (explode(' ', trim($str)) as $val)
    {
        $out .= $val.' ';

        if (strlen($out) >= $n)
        {
            $out = trim($out);
            return (strlen($out) == strlen($str)) ? $out : $out.$end_char;
        }
    }
 }

You can use the function:

echo character_limiter($text, 200);

If you need to avoid HTML tags, you can use strip_tags function before calling the character_limiter function.

Answer by Starx

There is a simple function called substr($string, $position, $length), which can do this.

Use it like

$brief = substr($bigContent, 0, 200); //for 200 chars
April 16, 2012

php function arguments

Question by Clint Chaney

I don’t know how or where I got this idea in my head but for some reason I thought this was possible. Obviously after testing it doesn’t work, but is there a way to make it work? I want to set $value2 without having to enter anything at all for $value1.

function test($value1 = 1, $value2 = 2) {

echo 'Value 1: '.$value1.'<br />';
echo 'Value 2: '.$value2.'<br />';

}

test($value2 = 3);

// output
Value 1: 3
Value 2: 2

Answer by rami

What you’re trying to do is called “keyword arguments” or “named arguments” and is not available in PHP in contrast to other scripting languages like Python.

If you have functions with hundreds of parameters and really want to achieve a more flexible solution than what PHP comes with, you could build your own workaround with arrays or objects, maybe in conjunction with func_get_args(). But this obviously isn’t as beautiful as real keyword arguments.

Answer by Starx

Its not entirely possible the way you want.

Simply,

function test($value1 = null, $value2 = 2) {

echo 'Value 1: '.$value1.'<br />';
echo 'Value 2: '.$value2.'<br />';

}

test(NULL, $value2 = 3);

Or, Use array as parameters

function test($array) {

if(isset($array['value1'])) echo 'Value 1: '.$array['value1'].'<br />';
if(isset($array['value2'])) echo 'Value 2: '.$array['value2'].'<br />';

}

test(array('value2' => 3));

Update:

My another attempt

function test() {
  $args = func_get_args();
  $count = count($args);
  if($count==1) { test1Arg($args[0]); }
  elseif($count == 2) { test2Arg($args[0],$args[1]); }
  else { //void; }
}

function test1Arg($arg1) {
   //Do something for only one argument
}
function test2Arg($arg1,$arg2) {
   //Do something for two args
}
April 7, 2012

jquery run functions

Question by user1022585

I have a function in jquery:

$('#map').click(function(e) {
    var posX = $(this).offset().left, posY = $(this).offset().top;
    if (posY < 100) {
       // do this

When the user clicks within that element it will run. But I also want it to run if he presses a cursor key.

Is it possible to do something like:

$('#map').click OR key.press(function(e) {

Basically, can you set more than one event to run that function?
Just learning jquery so go easy on me.

UPDATE

function move(e) {
   var posX = $(this).offset().left, posY = $(this).offset().top;

    if (posX > 75 && posX < 150 && posY < 75) { var go = "N"; }
    if (e.which == 38) { var go = "N"; }

    $.post("inc_map.php", { move: go }, function(data){ 
        var substr = data.split('@'); 
        if (substr[0] != "block") {
            var x1 = substr[0]; var y1 = substr[1];
            x = parseInt(x1) * 32; y = parseInt(y1) * 32;
            $("#mapview").css({ backgroundPosition: -x + "px " + -y + "px" });
                $("#map").html(substr[2]);
                $("#info").html(substr[3]);
                };
            $("#pos").html((x/32) + ', ' + (y/32)); 
        });  

};



$("#map").click(move).keypress(move);

Why doesnt this work? 😮

Answer by Elliot Bonneville

You’d define a function outside of the event handlers, then call it from each handler separately.

function myFunc(e) {
    var posX = $(this).offset().left, posY = $(this).offset().top;
    if (posY < 100) {

    }

    // if e.which equals 38, the up arrow was pressed
    if(e.which == 38) {
        // do nice stuff here
    }

    // the rest of your function here...
}

$("#map").click(myFunc).keypress(myFunc);

Edit: Threw in jQuery function chaining, too.

Aha, okay. I think I found your error. I’ve reformatted your code a bit and neatened it up some. Try this:

function move(e) {
    var posX = $(this).offset().left,
    var posY = $(this).offset().top;

    var go = "";

    if (posX > 75 && posX < 150 && posY < 75) {
        go = "N";
    }

    if (e.which == 38) {
        go = "N";
    }

    $.post("inc_map.php", {
        move: go
    }, function(data) {
        var substr = data.split('@');
        if (substr[0] != "block") {
            var x1 = substr[0];
            var y1 = substr[1];
            x = parseInt(x1) * 32;
            y = parseInt(y1) * 32;
            $("#mapview").css({
                backgroundPosition: -x + "px " + -y + "px"
            });
            $("#map").html(substr[2]);
            $("#info").html(substr[3]);
        };
        $("#pos").html((x / 32) + ', ' + (y / 32));
    });

};

Answer by Starx

Pass a common event handler between clicks and keypresses

For example:

function myFunc(e) {
   //For cursor
   switch(e.charCode) {
      case 37: 
         // Left
      break;
      case 37: 
         // Up
      break;
      case 37: 
         // Right
      break;
      case 37: 
         // Down
      break;
   }
}

$("#map").click(myfunc).keypress(myfunc);
April 3, 2012

if/else statement in a function: using onclick as a switch

Question by Aurora Schmidt

I have looked for solutions to this on google for what seems like an eternity, but I can’t seem to formulate my search correctly, or nobody has posted the code I’m looking for earlier.

I am currently trying to make a function that will modify one or several margins of a div element. I want to use an if/else statement within the function, so that the onclick event will switch between the two conditions. This is what I have been working on so far;

function facebookToggle()
{
    if($('#facebooktab').style.margin-left == "-250px";)
    {
        document.getElementById("facebooktab").style.marginLeft="0px";
    }
    else
    {
        document.getElementById("facebooktab").style.marginLeft="-250px";
    }
}

I have tried twisting it around a little, like switching between “marginLeft” and “margin-left”, to see if I was just using the wrong terms.. I’m starting to wonder if it might not be possible to combine jQuery and regular javascript? I don’t know.. It’s all just guesses on my part at this point.

Anyway, I have a div, which is now positioned (fixed) so almost all of it is hidden outside the borders of the browser. I want the margin to change onclick so that it will be fully shown on the page. And when it is shown, I want to be able to hide it again by clicking it.

I might be approaching this in the wrong way, but I really hope someone can help me out, or even tell me another way to get the same results. Thank you for any help you can give me.

You can see it in action at: http://www.torucon.no/test/

(EDIT: By the way, I am a complete javascript novice, I have no experience with javascript prior to this experiment. Please don’t be too harsh, as I am aware I probably made some really stupid mistakes in this short code.)

Fixed problem:

function facebookToggle() {
var fb = $('#facebooktab'); // save reference to element
if( fb.css('margin-left') === '-250px' ) {
    fb.css('margin-left', '0px');
} else {
    fb.css('margin-left', '-250px');
}
}

Answer by paislee

A jQuery object doesn’t have a property called style, so

if($('#facebooktab').style.margin-left == "-250px";)
//                   also remove this semi-colon! ^

is going to throw an error. Some options for accessing CSS properties are (1)

document.getElementById("facebooktab").style.marginLeft;

which you have correctly used, or (2)

$('#facebooktab').css('margin-left');

Consider being consistent and using the same approach for all three cases. You can assign css properties with jQuery like

$('#facebooktab').css('margin-left', '-250px');

With these things in mind, here’s a suggested rewrite:

function facebookToggle() {
    var fb = $('#facebooktab'); // save reference to element
    if( fb.css('margin-left') === '-250px' ) {
        fb.css('margin-left', '0px');
    } else {
        fb.css('margin-left', '-250px');
    }
}

and here’s another that uses a predefined CSS class:

#facebooktab {
    margin-left: -250px; /** default state */
}

.no-left-margin {
    margin-left: 0px;
}
function facebookToggle() {
    $('#facebooktab').toggleClass('no-left-margin');
}

Answer by Starx

Since you are mixing jQuery with javascript, you got mixed up. Apart from what paislee’s advice. you are do this too.

if($('#facebooktab')[0].style.margin-left == "-250px";){
    document.getElementById("facebooktab").style.marginLeft="0px";
}
else    {
    var fb = document.getElementById("facebooktab");
    fb.style.marginLeft="-250px";
}
March 25, 2012

setTimeout within function fails

Question by user1019490

This function accepts an argument, whichImage. This is the object HTMLImageElement for the image we are working with. The image width will be halved, and then after 3 seconds, it will return to normal width. However, the setTimeout code, which is supposed to execute after 3 seconds, fails, with the error message that whichImage is not defined. What do I need to correct to make this function work?

function resizeImageFunction(whichImage){
    // Get the width of the image
    alert(whichImage);
    var width = whichImage.width;
    var halfwidth = Math.round(width/2);
    whichImage.width=halfwidth;
    setTimeout("whichImage.width=width;",3000);
}

Answer by Starx

You don’t need to use eval for this

setTimeout(function() { whichImage.width=width; } ,3000);

Here is is your function

function resizeImageFunction(whichImage){
    var halfwidth = Math.round(width/2);
    whichImage.width=halfwidth;
    setTimeout(function() { whichImage.width=width; } ,3000);
}
March 24, 2012

jQuery play/pause jQuery function

Question by Yusaf

What I’m trying to do is play and pause a function ie press a button to start a fucntion press a button to pause so on. I am not entirely sure how this can be done i have tried .live() and .die() but they don’t work.

Fiddle

I have the HTML below

<button class="play">play</button>
<button class="pause">pause</button>
<div class="divafter"></div>​

and the jQuery which I’m not entirely sure what .die() does but on the jsfiddle seems to speed up the interval time.

(function($){
  playing = function() {
window.setInterval(function() {
    $(".divafter").after("playing <br/>");
}, 500);
};
})(jQuery);
$(".play").click(function(){
    playing().live();
});
$(".pause").click(function(){
    playing().die();
});​

Answer by j08691

Try this jsFiddle example. You need to use clearInterval() to stop setInterval().

jQuery:

var foo;
playing = function() {
    foo = window.setInterval(function() {
        $(".divafter").after("playing <br/>");
    }, 500);
}

$(".play").click(function() {
    playing();
});
$(".pause").click(function() {
    clearInterval(foo);
});​

Answer by Starx

You will have to the clearInterval to simulate the pause effect.

Grab the instance of the interval like this

playing = setInterval(function() {
            $(".divafter").after("playing <br/>");
          }, 500);

And clear to pause

clearInterval(playing);

Usage on your code would be this:

var playstatus;
(function($){
    playing = function() {
        return setInterval(function() {
           $(".divafter").after("playing <br/>");
           }, 500);
    };

})(jQuery);

$(".play").click(function(){
    playstatus = playing();
});
$(".pause").click(function(){
   clearInterval(playstatus);
});

Demo

function not being called, using jquery .delegate

Question by monkey blot

I want to use jquery delegate to call a function, and this works fine:

$("body").delegate("div", "mouseover", function(){
alert("it works");
});

But I also want to be able to use the same function elsewhere. So rather than writing the same function out several times, I can just declare it separately, and call it by name, right?

But written this way, I never see the alert.

function alertMe(){
alert("it works");
};

$("body").delegate("div", "mouseover", alertMe());

Answer by tusar

Drop the parenthisis while defining delegate. just give the function-name

$("body").delegate("div", "mouseover", alertMe);

Answer by Starx

Creating the common event handler is easy

function alertMe(event){
    //you also need to include the event object, for various actions like stopPropagation()
    alert("it works");
};

$("body").delegate("div", "mouseover", alertMe);
...

Please fill the form - I will response as fast as I can!