Shortcut for: $foo = explode(" ", "bla ble bli"); echo $foo[0] - php

is there a way to get the n-th element of a splitted string without using a variable?
My PHP code always looks like this:
$foo = explode(" ", "bla ble bli");
echo $foo[0];
Is there a shorter way maybe like in Python?
print "bla ble bli".split(" ")[0]
Thanks in advance.

This is what people should be using instead of explode most of the time:
$foo = strtok("bla ble bli", " ");
It cuts off the first string part until the first " ".
If you can't let go of explode, then the closest idiom to accomplish [0] like in Python is:
$foo = current(explode(...));
If it's not just the first element, then it becomes a tad more cumbersome:
$foo = current(array_slice(explode(...), 2)); // element [2]

(Not really an answer per se -- others did answer pretty well)
This is one of the features that should arrive with one of the next versions of PHP (PHP 5.4, maybe).
For more informations, see Features in PHP trunk: Array dereferencing -- quoting one of the given examples :
<?php
function foo() {
return array(1, 2, 3);
}
echo foo()[2]; // prints 3
?>

try this:
its one line:
<?php
echo (($f=explode(" ", "bla ble bli"))?$f[0]:'');
?>
result here:
http://codepad.org/tnhbpYdd

Why not just do:
function splode($string, $delimiter, $index){
$r = explode($delimiter, $string);
return $r[$index];
}
I use like a hojillion little functions like this.

With only one expression I can think of:
echo list($a) = explode(' ', 'a b c') ? $a : '';
echo list($_, $b) = explode(' ', 'a b c') ? $b : '';

Not as far as I know although you could define a function and use that.
function firstWord($string) {
$foo = explode(" ", $string);
return $string;
}

I don't know of a way to do what you want, even though I've wanted to do the same thing many times before. For that specific case you could do
$bar = substr($foo, 0, strpos($foo, " "));
which stops there being one extra variable, but isn't exactly what you wanted.

The following is probably the cleanest way I can think of doing what OP has requested. It defines a function, but no variables of it's own and it'll get the job done for just about any situation:
function at(&$arr, &$pos) { return $arr[$pos]; }
Example usage:
echo at( explode('|', 'a|b|c|d'), 1 ); // Outputs 'b'
The function is a single line of code and wouldn't be hard to commit to memory. If you're only using it once, you can define it in the local scope of where it'll be used to minimize code clutter.
As a slight added benefit, because the function does no checks on $arr or $pos, it'll throw all the same errors that it would if you tried to access a non-existent index for an array, or will even return the individual characters in a string or items in a key-value paired array.

close. the right track is making a function or method for something that gets repeated.
function extract_word($input, $index) {
$input = explode(' ', $input);
return $input[$index];
}
add a third argument of $separater = ' ' if you may have different word separaters.

Related

How to use explode and get first element in one line in PHP?

$beforeDot = explode(".", $string)[0];
This is what I'm attempting to do, except that it returns syntax error. If there is a workaround for a one liner, please let me know. If this is not possible, please explain.
The function array dereferencing was implemented in PHP 5.4, so if you are using an older version you'll have to do it another way.
Here's a simple way to do it:
$beforeDot = array_shift(explode('.', $string));
You can use list for this:
list($first) = explode(".", "foo.bar");
echo $first; // foo
This also works if you need the second (or third, etc.) element:
list($_, $second) = explode(".", "foo.bar");
echo $second; // bar
But that can get pretty clumsy.
Use current(), to get first position after explode:
$beforeDot = current(explode(".", $string));
Use array_shift() for this purpose :
$beforeDot = array_shift(explode(".", $string));
in php <= 5.3 you need to use
$beforeDot = explode(".", $string);
$beforeDot = $beforeDot[0];
2020 : Google brought me here for something similar.
Pairing 'explode' with 'implode' to populate a variable.
explode -> break the string into an array at the separator
implode -> get a string from that first array element into a variable
$str = "ABC.66778899";
$first = implode(explode('.', $str, -1));
Will give you 'ABC' as a string.
Adjust the limit argument in explode as per your string characteristics.
You can use the limit parameter in the explode function
explode($separator, $str, $limit)
$txt = 'the quick brown fox';
$explode = explode(' ', $txt, -substr_count($txt, ' '));
This will return an array with only one index that has the first word which is "the"
PHP Explode docs
Explanation:
If the limit parameter is negative, all components except the last
-limit are returned.
So to get only the first element despite the number of occurences of the substr you use -substr_count

Php split a string to to string

I want to split a variable that I call for $ NowPlaying which contains the results of the current song. I would now like to share the following - so I get two new variables containing $ artist $ title. Having searched and tried to find a solution, but have stalled grateful for a little assistance, and help
<?php
// Assuming $NowPlaying is something like "J. Cole - Chaining Day"
// $array = explode("-", $NowPlaying); //enter a delimiter here, - is the example
$array = explode(" - ", $NowPlaying); //DJHell pointed out this is better
$artist = $array[0]; // J. Cole
$song = $array[1]; // Chaining Day
// Problems will arise if the delimiter is simply (-), if it is used in either
// the song or artist name.. ie ("Jay-Z - 99 Problems") so I advise against
// using - as the delimiter. You may be better off with :.: or some other string
?>
Sounds like you're wanting to use explode()
http://php.net/manual/en/function.explode.php
Use php explode() function
$str_array = explode(' - ', $you_song);
// then you can get the variables you want from the array
$artist = $str_array[index_of_artist_in_array];
$title = $str_array[index_of_title_in_array];
I would usually do some thing like this:
<?php
$input = 'Your - String';
$separator = ' - ';
$first_part = substr($input, 0, strpos($input, $separator));
$second_part = substr($input, (strpos($input, $separator) + strlen($separator)), strlen($input));
?>
I have looked at a couple split string questions and no one suggests using the php string functions. Is there a reason for this?
list() is made for exactly this purpose.
<?php
list($artist, $title) = explode(' - ', $NowPlaying);
?>
http://php.net/manual/en/function.list.php

php: Delete specific index from string?

I want to be able to specify an index in a string and remove it.
I have the following:
"Hello World!!"
I want to remove the 4th index (o in Hello). Here would be the end result:
"Hell World!!"
I've tried unset(), but that hasn't worked. I've Googled how to do this and that's what everyone says, but it hasn't worked for me. Maybe I wasn't using it right, idk.
This is a generic way to solve it:
$str = "Hello world";
$i = 4;
echo substr_replace($str, '', $i, 1);
Basically, replace the part of the string before from the index onwards with the part of the string that's adjacent.
See also: substr_replace()
Or, simply:
substr($str, 0, $i) . substr($str, $i + 1)
$str="Hello World";
$str1 = substr($str,0,4);
$str2 = substr($str,5,7);
echo $str1.$str2;
This php specific of working with strings also bugged me for a while. Of course natural solution is to use string functions or use arrays but this is slower than directly working with string index in my opinion. With the following snippet issue is that in memory string is only replaced with empty � and if you have comparison or something else this is not good option. Maybe in future version we will get built in function to remove string indexes directly who knows.
$string = 'abcdefg';
$string[3] = '';
var_dump($string);
echo $string;
$myVar = "Hello World!!";
$myArray = str_split($myVar);
array_splice($myArray, 4, 1);
$myVar = implode("", $myArray);
Personal I like dealing with arrays.
(Sorry about lack of code brackets putting this up via my phone)
I think can create a function and call it like this
function rem_inx ($str, $ind)
{
return substr($str,0,$ind++). substr($str,$ind);
}
//use
echo rem_inx ("Hello World!!", 4);

Remove token variables

I'm in the process of writing a theme based script and need a way to replace "variables" or tokens that weren't replaced by the script.
The format is:
^_variablename_^
So say, after processing the following, with variables: name=Adam, Occupation=programmer
Hello, my name is ^_title_^^_name_^, and I work as a ^_occupation_^.
We'd be left with ^_title_^ still in place.
I need a way to get rid of these, without knowing the name of the "variable".
Thanks in advance :)
Process again:
$str = 'Hello, my name is ^_title_^Adam, and I work as a programmer.';
$str = preg_replace('/\^_(\w+)_\^/', '', $str);
echo $str;
Codepad
$str = 'Hello, my name is ^_title_^Adam, and I work as a programmer.';
echo preg_replace('/^_[\w_-]+_^/i', '', $str);
Try using preg_replace_callback, when substitute variables in so you can simply ignore ones you can't substitute in:
$input = 'Hello, my name is ^_title_^^_name_^, and I work as a ^_occupation_^. ';
$variables = array('name' => 'adam');
$re = preg_replace_callback('/\^_(?<var>.+?)_\^/', function($params) use ($variables) {
if (isset($variables[$params['var']])) {
return $variables[$params['var']];
} else {
return '';
}
},
$input);
print $re;
This uses anonymous function syntax that works since php 5.3.0, you might need to declare a separate callback for this if you want to use it on earlier versions.

Is it possible to create a variable variable from a back reference in php?

Suppose I have this:
$t = "This %var% should be replaced";
$newText = preg_replace('/%(.+?)%/', "$1", $t);
What that does is replace the %var% for var, so the text becomes:
This var should be replaced.
But what I want to do is have a variable named $var, and then replace "%var%" with the value of $var.
We know that we can create variable variables like this:
$foo = "one";
$$foo = "two"
echo $one; //prints "two"
If you don't know about this, then you might not be able to answer my question. But you can read more about variable variables on http://www.php.net/manual/en/language.variables.variable.php
Well, that does not work in this case. If I do this:
$t = "This %var% should be replaced";
$newText = preg_replace('/%(.+?)%/', $"$1", $t);
I get an error.
I also tried like this:
$t = "This %var% should be replaced";
$newText = preg_replace('/%(.+?)%/', ${$1}, $t);
And I get another error.
The question is: how would I create a variable variable to replace %var% with the value of $var?
Some of you might ask why not just do this:
$t = "This %var% should be replaced";
$newText = preg_replace('/%(.+?)%/', $var, $t);
The reason is simple. The text I have is more complex than that. Lets make it more fun, shall we?
$text = "This %var% should be replaced, just like this %foo%;
$newText = preg_replace('/%(.+?)%/', "$1", $text);
As you can see, we need to replace %var% with the value of $var, and %foo% with the value of $foo.
I already solved the problem, but in a different way. But I am still wondering how it would be possible to solve it in this way, since the code is more readable. If it is not possible to solve it, then why?
Thanks for al your answers ans interest. Like I said I already solved the problem in a different way, and yes, I used preg_repace_callback. I am not looking for a solution to the problem, but for an explanation on why it is not possible to create a variable variable out of the backreference. I'm sorry if my question was confusing, or badly written and made you guys think I was still looking for a solution on how to achieve my goal.
If you wish to see how I solved it, you can go to my blog, I posted there yesterday about this: http://imbuzu.wordpress.com/2012/02/07/back-references-in-php-how-to-create-variable-variables-using-them/
Again. I am not looking for a way to do this, but rather for an explanation on why it is not possible to do it the way I initially intended. Why is it that you can't create a variable variable from the backreference?
To the Admins. This reply is a general reply to all the answers above. IF you are going to edit it and add it as a comment to any of them, please add it to all of them, or at least notify the users of this reply. Thanks.
What about an associative array?
$replacement = array('var' => 'value1',
'foo' => 'value2');
$text = "This %var% should be replaced, just like this %foo%";
$newText = preg_replace('/%(.+?)%/', $replacement[$1], $text);
You could use preg_replace_callback():
$var = '[replaced]';
function handler($found)
{
if ( isset($GLOBALS[$found[1]]) )
return $GLOBALS[$found[1]];
else
return $found[0];
}
$text = 'This %var% should be replaced and this %var2% will not be replaced!';
$newText = preg_replace_callback('/%(.+?)%/', 'handler', $text);
echo $newText;
This outputs the following:
This [replaced] should be replaced and this %var2% will not be replaced!
You must create a small parser with preg_X functions and an eval call. With these ingredients you can cook something like this:
<?php
$var = 'world';
$end = '.';
$t = "This %var% should be replaced%end%";
//We should escape " character
$t = str_replace('"','\"',$t);
$php = $t;
do
{
$orig_php = $php;
$php = preg_replace('/%([^%]+)%/','$\\1',$t);
} while($php!=$orig_php);
eval('$output="'.$php.'";');
echo($output);
?>
It's a tiny template engine

Categories