PHP :taking sub strings from given string - php

I have string in the following format.
Option1:Option2:Option3:Option4
I want to get these items separated and put it into a array.
array(item1=>option1,item2=>option2,item3=>option3,item4=>option4)
etc.
is there a straight forward way to get this done using regular expressions with PHP.
Thanks in advance for sharing your experience with me.

Use $arr = explode(":", $string); and then do this:
$result = array();
for ($i = 0; $i < count($arr); $i ++) {
$result['item' . $i] = $arr[$i];
}
and you should find $result to be exactly what you want

You can use explode function for that
$array = explode(":", $str);

Related

Mix array with ancestor elements

Seems to be very simple but I'm like, losing a lot of time on this... and no success...
If I have a string:
$str = "She sells seashells"
So I turn every word into an array element
$array = explode(" ", $str);
What I need is, every word receive the ancestor element (if any) and the next ones...
Example result in json format (more easy to show)
"{"She":["sells","seashells"],"sells":["She","seashells"],"seashells":["She","sells"]}"
Can somebody help?
Thanks!
Really, you can copy a source array for each key, excluding that key:
$str = "She sells seashells";
$array = explode(" ", $str);
$res = [];
for($i = 0; $i < count($array); $i++) {
$res[$array[$i]] = $array;
unset($res[$array[$i]][$i]);
}
print_r($res);
demo
<?php
$str = "She sells seashells";
$arr = explode(" ",$str);
$length = count($arr);
$result = [];
for($i = 0;$i < $length;++$i){
$result[$arr[$i]] = [];
foreach ($arr as $each_val) {
if($each_val === $arr[$i]) continue;
$result[$arr[$i]][] = $each_val;
}
}
echo json_encode($result);
OUTPUT:
{"She":["sells","seashells"],"sells":["She","seashells"],"seashells":["She","sells"]}
Explode the string based on spaces.
Have a result array and make the current iteration value in for loop as the key for it.
Loop again over the array and check if current value matches with outer for loop value. If yes, then continue, else add that value in this result array key.
In the end, json_encode() it and you are done.

Using an index twice in PHP

I am trying to use a for loop where it looks through an array and tries to make sure the same element is not used twice. For example, if $r or the random variable is assigned the number "3", my final array list will find the value associated with wordList[3] and add it. When the loop runs again, I don't want $r to use 3 again. Example output: 122234, where I would want something along the lines of 132456. Thanks in advance for the help.
for($i = 0; $i < $numWords; $i++){
$r = rand(0, $numWords);
$arrayTrack[$i] == $r;
$wordList[$r] = $finalArray[$i];
for($j = 0; $j <= $i; $j++){
if($arrayTrack[$j] == $r){
# Not sure what to do here. If $r is 9 once, I do not want it to be 9 again.
# I wrote this so that $r will never repeat itself
break;
}
}
Edited for clarity.
Pretty sure you are over complicating things. Try this, using array_rand():
$final_array = array();
$rand_keys = array_rand($wordList, $numWords);
foreach ($rand_keys as $key) {
$final_array[] = $wordList[$key];
}
If $numWords is 9, this will give you 9 random, unique elements from $wordList.
See demo
$range = range(0, $numWords - 1); // may be without -1, it depends..
shuffle($range);
for($i = 0; $i < $numWords; $i++) {
$r = array_pop($range);
$wordList[$r] = $finalArray[$i];
}
I do not know why you want it.. may be it is easier to shuffle($finalArray);??
So ideally "abcdefghi" in some random order.
$letters = str_split('abcdefghi');
shuffle($letters);
var_dump($letters);
ps: if you have hardcoded array $wordList and you want to take first $n elements of it and shuffle then (if this is not an associative array and you do not care about the keys)
$newArray = array_slice($wordList, 0, $n);
shuffle($newArray);
var_dump($newArray);
You can try array_rand and unset
For example:
$array = array('one','two','free','four','five');
$count = count($array);
for($i=0;$i<$count;$i++)
{
$b = array_rand($array);
echo $array[$b].'<br />';
unset($array[$b]);
}
after you have brought the data in the array, you purify and simultaneously removing the memory array
Ok... I have NO idea why you are trying to use so many variables with this.
I certainly, have no clue what you were using $arrayTrack for.
There is a very good chance I am mis-understanding all of this though.
<?php
$numWords=10;
$wordList=array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
$finalArray=array();
for ($i=0; $i<$numWords; $i++) {
start:
$r=rand(0,$numWords);
$wordChoice=$wordList[$r];
foreach ($finalArray as $word) {
if ($word==$wordChoice) goto start;
}
$finalArray[]=$wordChoice;
}
echo "Result: ".implode(',',$finalArray)."\n";

How to expand a string with PHP, using the FROM and TO numbers specified within square brackets?

Let’s say I have the string http://www.example.com/images/[1-12].jpg. I would like to expand it into:
http://www.example.com/images/1.jpg
http://www.example.com/images/2.jpg
http://www.example.com/images/3.jpg
http://www.example.com/images/4.jpg
http://www.example.com/images/5.jpg
http://www.example.com/images/6.jpg
http://www.example.com/images/7.jpg
http://www.example.com/images/8.jpg
http://www.example.com/images/9.jpg
http://www.example.com/images/10.jpg
http://www.example.com/images/11.jpg
http://www.example.com/images/12.jpg
Here is my code:
$str = "http://www.example.com/images/[1-12].jpg";
while(preg_match_all("/^([^\\[\\]]*)\\[(\\d+)\\-(\\d+)\\](.*)$/m", $str, $mat)){
$arr = array();
$num = sizeof($mat[0]);
for($i = 0; $i < $num; $i++){
for($j = $mat[2][$i]; $j <= $mat[3][$i]; $j++){
$arr[] = rtrim($mat[1][$i].$j.$mat[4][$i]);
}
}
$str = implode(PHP_EOL, $arr);
}
It works fine even if I change $str to a more complex expression like the following:
$str = "http://www.example.com/images/[1-4]/[5-8]/[9-14].jpg";
But, unfortunately, zero-padded integers are not supported. So, if I begin with:
$str = "http://www.example.com/images/[001-004].jpg";
Expected result:
http://www.example.com/images/001.jpg
http://www.example.com/images/002.jpg
http://www.example.com/images/003.jpg
http://www.example.com/images/004.jpg
And the actual result:
http://www.example.com/images/001.jpg
http://www.example.com/images/2.jpg
http://www.example.com/images/3.jpg
http://www.example.com/images/4.jpg
How to change this behaviour so that my code produces the expected result? Also, what are the other shortcomings of my code? Should I really do it with the while loop and preg_match_all or are there faster alternatives?
UPDATE: Changing the seventh line of my code into
$arr[] = rtrim($mat[1][$i].str_pad($j, strlen($mat[2][$i]), 0, STR_PAD_LEFT).$mat[4][$i]);
seems to do the trick. Thanks a lot to sjagr for suggesting this. My question is still open because I would like to know the shortcomings of my code and faster alternatives (if any).
Per #SoumalyoBardhan's request, my suggestion/answer:
If you use str_pad(), you can force the padding based on the size of the matched string using strlen() found by your match. Your usage of it looks good to me:
$arr[] = rtrim($mat[1][$i].str_pad($j, strlen($mat[2][$i]), 0, STR_PAD_LEFT).$mat[4][$i]);
I really can't see what else could be improved with your code, although I don't exactly understand how preg_match_all would be used in a while statement.
A faster alternative with preg_split which also supports descending order (FROM > TO):
$str = "http://www.example.com/images/[12-01].jpg";
$spl = preg_split("/\\[([0-9]+)-([0-9]+)\\]/", $str, -1, 2);
$size = sizeof($spl);
$arr = array("");
for($i = 0; $i < $size; $i++){
$temp = array();
if($i%3 == 1){
$range = range($spl[$i], $spl[$i+1]);
$len = min(strlen($spl[$i]), strlen($spl[++$i]));
foreach($arr as $val){
foreach($range as $ran){
$temp[] = $val.str_pad($ran, $len, 0, 0);
}
}
}
else{
foreach($arr as $val){
$temp[] = $val.$spl[$i];
}
}
$arr = $temp;
}
$str = implode(PHP_EOL, $arr);
print($str);
It has the following result:
http://www.example.com/images/12.jpg
http://www.example.com/images/11.jpg
http://www.example.com/images/10.jpg
http://www.example.com/images/09.jpg
http://www.example.com/images/08.jpg
http://www.example.com/images/07.jpg
http://www.example.com/images/06.jpg
http://www.example.com/images/05.jpg
http://www.example.com/images/04.jpg
http://www.example.com/images/03.jpg
http://www.example.com/images/02.jpg
http://www.example.com/images/01.jpg

Take a part of a string (PHP)

We are trying to get certain parts of a String.
We have the string:
location:32:DaD+LoC:102AD:Ammount:294
And we would like to put the information in different strings. For example $location=32 and $Dad+Loc=102AD
The values vary per string but it will always have this construction:
location:{number}:DaD+LoC:{code}:Ammount:{number}
So... how do we get those values?
That would produce what you want, but for example $dad+Loc is an invalid variable name in PHP so it wont work the way you want it, better work with an array or an stdClass Object instead of single variables.
$string = "location:32:DaD+LoC:102AD:Ammount:294";
$stringParts = explode(":",$string);
$variableHolder = array();
for($i = 0;$i <= count($stringParts);$i = $i+2){
${$stringParts[$i]} = $stringParts[$i+1];
}
var_dump($location,$DaD+LoC,$Ammount);
Easy fast forward approach:
$string = "location:32:DaD+LoC:102AD:Ammount:294";
$arr = explode(":",$string);
$location= $arr[1];
$DaD_LoC= $arr[3];
$Ammount= $arr[5];
$StringArray = explode ( ":" , $string)
By using preg_split and mapping the resulting array into an associative one.
Like this:
$str = 'location:32:DaD+LoC:102AD:Ammount:294';
$list = preg_split('/:/', $str);
$result = array();
for ($i = 0; $i < sizeof($list); $i = $i+2) {
$result[$array[$i]] = $array[$i+1];
};
print_r($result);
it seems nobody can do it properly
$string = "location:32:DaD+LoC:102AD:Ammount:294";
list(,$location,, $dadloc,,$amount) = explode(':', $string);
the php function split is deprecated so instead of this it is recommended to use preg_split or explode.
very useful in this case is the function list():
list($location, $Dad_Loc, $ammount) = explode(':', $string);
EDIT:
my code has an error:
list(,$location,, $Dad_Loc,, $ammount) = explode(':', $string);

What's the fastest way to populate an array with numbers in PHP?

What's the fastest way to populate an array with the numbers 1-100 in PHP? I want to avoid doing something like this:
$numbers = '';
for($var i = 0; i <= 100; $i++) {
$numbers = $i . ',';
}
$numberArray = $numbers.split(',');
It seems long and tedious, is there a faster way?
The range function:
$var = range(0, 100);
range() would work well, but even with the loop, I'm not sure why you need to compose a string and split it - what's wrong with simply:
$numberArray = array();
for ($i = 0; $i < 100; $i++)
$numberArray[] = $i;

Categories