开发者

Any equivalent to .= for adding to beginning of string in PHP?

Just wondering if there is something like .= for adding text to 开发者_开发百科the beginning of a string, e.g.:

$foo =. 'bar';

which doesn't work.

Edit: example was originally $foo =. $bar; which can be achieved with $bar .= $foo;


Nope. But you can do

$foo = "bar" . $foo


You could always make your own function for that:

function prepend($string, $chunk) {
     if(!empty($chunk) && isset($chunk)) {
        return $string.$chunk;
     }
     else {
        return $string;
     }
}

$string would be the piece that you want to prepend and $chunk would be the text that you want something prepended onto it.

You could say the checks are optional, but by having that in there you don't need to worry about passing in a null value by accident.


I know this was asked/answered a while ago, but providing this answer as it is functionally equivalent despite it not being an assignment operator and no one commented on its usage for general string concatenation.

You may want to look into the use of the sprintf (documentation) family of functions for string concatenation. It provides a lot more sanitization and usability than just combining two strings with assignment operators.

$foo = 'foo';

$append = sprintf('%1$s%2$s', $foo, 'bar');
var_dump($append);
/* string(6) "foobar" */

$prepend = sprintf('%1$s%2$s', 'bar', $foo);
var_dump($prepend);
/* string(6) "barfoo" */

$prependInvert = sprintf('%2$s%1$s', $foo, 'bar');
var_dump($prependInvert);
/* string(6) "barfoo" */

$wrap = sprintf('%2$s%1$s%2$s', $foo, 'bar');
var_dump($wrap);
/* string(6) "barfoobar" */

I normally use vsprintf, since working with arrays is easier to manage value positions than individual arguments.

$vprepend = vsprintf('%2$s%1$s', array('foo', 'bar'));
var_dump($vprepend);
/* string(6) "barfoo" */

Also with an array of values, one can simply implode the resultant set of values for simple string concatenation.

 var_dump(implode('', array('bar', 'foo')));
 /* string(6) "barfoo" */


You can wrap the built-in function substr_replace, where the arguments $start and $length can be set to 0, which prepends the $replacement to $string and returns the result, like so:

function prepend(& $string, $prefix) {
    $string = substr_replace($string, $prefix, 0, 0);
}

An example usage of the helper function would be:

$email_message = "Jonathan";
$appropriate_greeting = "Dear ";
prepend($email_message, $appropriate_greeting);
echo $email_message;

If you are into procedural programming, that is.


Turning Blakethepatton's comment into an answer (thank you), a way to do this more neatly for longer variable names is by using a reference to the variable as follows:

$f = &$foo; $f = "bar{$f}";

This will save you typing over the answer by Eric V if your original variable name is 12 characters or longer.

An alternative on one line:

$f = 'bar' . ($f = &$foo);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜