I have a weird project I'm working on. I'm totally new to php so it has been a struggle so far.
I have a form that gives an array and posts it:
...
return($keywords);
}
$keywordlist = explode("\r\n", $keywordlist);
foreach($keywordlist as $keyword){
print_r(mixer(strtolower($keyword)));
}
I get this:
Array ( [0] => one [1] => two [2] => three [3] => four [4] => five [5] => six [6] => ....
But would like it to come out like this instead:
%28one%2Ctwo%2Cthree%2Cfour%2Cfive%2Csix%29
Ultimately hope to be able to attach it to the end of a url like ask.com search:
"http://www.ask.com/web?q=(put my keywords here)"
then navigate there
In theory it would be like I typed "(one,two,three,four,five,six)" into the search bar and pressed enter.
Hopefully that makes some sense.
Something like this:
$commaSeparated = implode(',', $array);
$withParens = '(' + $commaSeparated + ')';
$urlEncoded = urlencode($withParens);
print $urlEncoded;
Use the php implode() function.
So you could do this:
$array = new array ( [0] => one [1] => two [2] => three [3] => four [4] => five [5] => six );
$string = '%28'.implode( '%2C', $array ).'%29';
Now $string will be what you need
This code:
$keywords = array('one', 'two', 'three');
$query = '(' . implode(',', $keywords) . ')';
echo('Search query: ' . $query . PHP_EOL);
$query = rawurlencode($query);
echo('Encoded: ' . $query . PHP_EOL);
Gives this output:
Search query: (one,two,three) Encoded:
%28one%2Ctwo%2Cthree%29
$keywordlist = explode("\r\n", $keywordlist);
array_walk($keywordlist, 'strtolower');
$keywords = '('.implode(",", $keywordList).')';
print_ris what prints your array like this.
http://php.net/manual/en/function.print-r.php
How to solve it depends on a few things. What does mixer()do? And is the keywords always in lowercase? If mixer doens't do much and the keywords are in lowercase you could do something like:
$string = '%28' . implode('%2C',
$keyword) . '%29';
If it's URL encoding you are after you could use the function url_encode instead of manually adding encoded values as above.
Something like this?
$input = array('one', 'two', 'three');
$s = implode(',', $input);
$s = '('.$i.')';
print urlencode($s);
You could encode each part of the array using urlencode and then manually put it in your url (making a url string by yourself). http://php.net/manual/en/function.urlencode.php
Or you could use this function instead: http://php.net/manual/en/function.http-build-query.php
Related
Whith this code I'm trying to split a string in the "//" but it only gives me a value on the $splits[1] and on the $splits[0] gives me nothing.
while($row = $result->fetch_assoc()) {
$amigos[] = $row["Id2"]."//".$row["ID"];
}
foreach ($amigos as $i => $value) {
$splits = preg_split("//", $value);
$IDAmizade = $splits[0];
$IDAmigo = $splits[1];
$sql = "SELECT `Nome`,`Agrupamento` FROM `Users` WHERE `ID`='$IDAmigo'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
echo($row["Nome"] . "+" . $row["Agrupamento"] . "+". $IDAmizade . "/");
}
And yes the $_row["Id2"] is returning a number i've confirm that.
The string that i'm trying to split is like: "1//3"
and after the split it gives me splits[0] is nothing and splits[1] is 3
what am I doing wrong?
The reason the 0 index is empty is because when using preg_split in this part preg_split("//", the first argument is the regex which uses / as a delimiter so you are splitting the string on an empty string.
$pattern = "//";
$string = "1//3";
print_r(preg_split($pattern, $string));
Output
Array
(
[0] =>
[1] => 1
[2] => /
[3] => /
[4] => 3
[5] =>
)
If you want to use preg_split with / as a delimiter and split on // you have to escape the forward slash.
$pattern = "/\/\//";
If you would use another delimiter like ~ the pattern would look like
$pattern = "~//~";
As already pointed out, you could use explode instead
$string = "1//3";
print_r(explode("//", $string));
Output
Array
(
[0] => 1
[1] => 3
)
You need to change your preg_split pattern. What you're doing at the moment will split the string up into its component characters.
So
$splits = preg_split("//", $value);
Should be:
$splits = preg_split("[//]", $value);
See more about preg_split here, and more about regular expressions here.
Alternatively, you could use explode, which splits a string by another string.
$splits = explode("//", $value);
As said in comment, why do you have 2 loops? A single one is enough and you don't need to split a string:
while($row = $result->fetch_assoc()) {
$sql = "SELECT `Nome`,`Agrupamento` FROM `Users` WHERE `ID`='" . $row["ID"] . "'";
$result2 = $conn->query($sql);
$row2 = $result2->fetch_assoc();
echo($row2["Nome"] . "+" . $row2["Agrupamento"] . "+". $row["Id2"] . "/");
}
Moreover you'd better use a JOIN instead of doing a second SELECT in the loop. I can't say more because we don't know the schema of the database and what is the database.
I dont really no how to start my steatment to output my expected result but in my achievement i have a hug string characters line example
$string = 'newboy1fineboy8badboy12 boy4andothers...';
my problem is how do i get all the boy and related characters from the string line example:
my expected result should be boy1boy8boy12boy4
Big thanks for time and impact in my solution
You can use preg_match_all and then foreach to display all data as per your requirement like below:
<?PHP
$string = 'newboy1fineboy8badboy12 boy4andothers...';
$string = preg_match_all('/boy\d+/', $string, $results);
foreach($results[0] as $val){
echo $val;
echo "<br>";
}
// Output
boy8
boy12
boy4
?>
Or if you want to get all your required data in 1 string then like below:
foreach($results[0] as $val){
$updated_string .= $val;
$updated_string .= " ";
}
echo $updated_string;
// Output
boy8 boy12 boy4
If you want to get data like runboy8 runboy12 runboy4 then you have to use str_replace like below to further update your string:
$updated_string = str_replace("boy","runboy",$string);
// Output will be runboy8 runboy12 runboy4
You can use preg_match_all() to do that:
<?php
$string = 'newboy1fineboy8badboy12 boy4andothers...';
preg_match_all('/boy\d+/', $string, $results);
print_r($results);
Then you can access the list of matching strings as $results[0]:
Array
(
[0] => Array
(
[0] => boy1
[1] => boy8
[2] => boy12
[3] => boy4
)
)
How would I use regular expression with PHP to split the following string into 2 pars as depicted below:
String to be split: 4x330ml
Split into 4x330 and ml
I have tried the following but it does not return the accurate data:
$pdata = "4x330ml"
$data = preg_split('#(?<=\d)(?=[a-z])#i', $pdata);
Then I get something like 4 in $data[0] and x330 in $data[1]
EDIT: Please note that ml could also be cm, kg, etc. A little complicated, which I don't seem to find a solution.
EDIT: Also I have tried the following regex (which I prefer to use at this point) with incomplete results:
$pdata = "5x500ml";
$data = preg_split('/(\d+\.?\d+)|(\w+)i/', $pdata);
This returns:
Array
(
[0] => 5x
[1] => ml
)
500 from that string is not being returned...
Thanks,
You said it could be ml, cm, or kg. and that you don't have to use regex. So, assuming it is always 2 characters at the end, a very simple way to do this would be:
$string = "4x330ml";
$part1 = substr($string, 0, -2); //returns 4x330
$part2 = substr($string, -2, 2); //returns "ml"
This ought to give you what you want.
$pdata = "4x330cm";
$data = preg_match('/([^(ml|cm|kg)]*)(ml|cm|kg)/', $pdata, $group);
echo $group[0].' ';
echo $group[1].' ';
echo $group[2].' ';
Use the preg_match function, and store the results into an array. The 0 index will return the entire matched string. The $group[1] will return just "4x330". The $group[2]$ will return just the "cm".
I'd use preg_match:
$pdata = "4x330ml";
preg_match('/(\d+x\d+)(.*)/',$pdata, $m);
print_r($m);
Output:
Array
(
[0] => 4x330ml
[1] => 4x330
[2] => ml
)
Assuming the units will always be 2 characters long you can use this
$pdata = "4x330ml";
$strNumber = substr($pdata, 0, strlen($pdata)-2);
$strUnit = substr($pdata, strlen($pdata)-2,2);
echo $strNumber; //returns 4x330
echo $strUnit; //returns ml
you can do this without a regex
$string = '4x330ml';
$splitPoint = strrpos($string,'m');
$firstPart = substr($string,0,$string); //gets 4x330
$secondPart = substr($string,$splitPoint); //gets ml
I was able to solve this problem by using the following code:
$data = "4x500ml";
$pdata = preg_split('/(\d+x\d+)/', $data, NULL, PREG_SPLIT_DELIM_CAPTURE);
Which now prints:
array(
[0] =>
[1] => 4x500
[2] => ml
)
It looks like it is capturing the delimeter as array[1] and since the delimeter is actually the first section of the string I want to split, it is fine for now, until I find a better solution.
Thank you all for trying.
I am trying to create an array from a plain text variable like so in php:
$arraycontent = "'foo', 'bar', 'hallo', 'world'";
print_r( array($arraycontent) );
But it outputs the entire string as [0]
Array ( [0] => 'foo', 'bar', 'hallo', 'world' )
I would like 'foo' to be [0]
bar to be [1] and so on. Any pointers? Is this even possible?
YIKES, why are these all so long?
Here's a one liner:
explode("', '", trim($arraycontent, "'"));
If your string was like this:
$arraycontent = "foo, bar, hallo, world"
With only the commas separating, then you could use explode, like this:
$myArray = explode(", ", $arraycontent);
This will create an array of strings based on the separator you define, in this case ", ".
If you want to keep the string as is, you can use this:
$myArray = explode("', '", trim($arraycontent, "'"));
This will now use "', '" as the separator, and the trim() function removes the ' from the beginning and end of the string.
If this is PHP you could use:
$foo = "'foo', 'bar', 'hallo', 'world'";
function arrayFromString($string){
$sA = str_split($string); array_shift($sA); array_pop($sA);
return explode("', '", implode('', $sA));
}
print_r(arrayFromString($foo));
eval('$array = array('.$arraycontent.');');
Would be the shortest way.
$array = explode(',', $arraycontent);
$mytrim = function($string) { return trim($string, " '"); };
$array = array_map($mytrim, $array);
A safer and therefore better one. If you have different whitespace characters you would have to edit the $mytrim lambda-function.
Here is a variant that based on the input example would work, but there might be corner cases that is not handled as wanted.
$arraycontent = "'foo', 'bar', 'hallo', 'world'";
$arrayparts = explode(',', $arraycontent); // split to "'foo'", " 'bar'", " 'hallo'", " 'world'"
for each ($arrayparts as $k => $v) $arrayparts[$k] = trim($v, " '"); // remove single qoute and spaces in beggning and end.
print_r( $arrayparts ); // Array ( [0] => 'foo', [1] => 'bar', [2] => 'hallo', [3] => 'world' )
This should give what you want, but also note that for example
$arraycontent = " ' foo ' , ' bar ' ' ' ' ', 'hallo', 'world'";
Would give the same output, so the question then becomes how strict are the $arraycontentinput?
If you have to have input like this, I suggest trimming it and using preg_split().
$arraycontent = "'foo', 'bar', 'hallo', 'world'";
$trimmed = trim($arraycontent, " \t\n\r\0\x0B'\""); // Trim whitespaces and " and '
$result = preg_split("#['\"]\s*,\s*['\"]#", $trimmed); // Split that string with regex!
print_r($result); // Yeah, baby!
EDIT: Also I might add that my solution is significantly faster (and more universal) than the others'.
That universality resides in:
It can recognize both " and ' as correct quotes and
It ignores the extra spaces before, in and after quoted text; not inside of it.
Seems you are having problem while creating an array..
try using
<?php
$arraycontent = array('foo', 'bar', 'hallo', 'world');
print_r( array($arraycontent) );
?>
its output will be:
Array ( [0] => Array ( [0] => foo [1] => bar [2] => hallo [3] => world
) )
I'm beginner in php and I have string like this:
$test = http://localhost/biochem/wp-content/uploads//godzilla-article2.jpghttp://localhost/biochem/wp-content/uploads/life-goes-on-wpcf_300x111.jpg
And I want to split string to array like this:
Array(
[0] => http://localhost/biochem/wp-content/uploads//godzilla-article2.jpg
[1] => http://localhost/biochem/wp-content/uploads/life-goes-on-wpcf_300x111.jpg
)
What should I do?
$test = 'http://localhost/biochem/wp-content/uploads//godzilla-article2.jpghttp://localhost/biochem/wp-content/uploads/life-goes-on-wpcf_300x111.jpg';
$testurls = explode('http://',$test);
foreach ($testurls as $testurl) {
if (strlen($testurl)) // because the first item in the array is an empty string
$urls[] = 'http://'. $testurl;
}
print_r($urls);
You asked for a regex solution, so here you go...
$test = "http://localhost/biochem/wp-content/uploads//godzilla-article2.jpghttp://localhost/biochem/wp-content/uploads/life-goes-on-wpcf_300x111.jpg";
preg_match_all('/(http:\/\/.+?\.jpg)/',$test,$matches);
print_r($matches[0]);
The expression looks for parts of the string the start with http:// and end with .jpg, with anything in between. This splits your string exactly as requested.
output:
Array
(
[0] => http://localhost/biochem/wp-content/uploads//godzilla-article2.jpg
[1] => http://localhost/biochem/wp-content/uploads/life-goes-on-wpcf_300x111.jpg
)
you can split them if they are always like this vith substr() function reference: http://php.net/manual/en/function.substr.php but if they are dynamic in lenght. you need to get a ; or any other sign that is not likely to be used there before 2nd "http://" and then use explode function reference: http://php.net/manual/en/function.explode.php
$string = "http://something.com/;http://something2.com"; $a = explode(";",$string);
Try the following:
<?php
$temp = explode('http://', $test);
foreach($temp as $url) {
$urls[] = 'http://' . $url;
}
print_r($urls);
?>
$test = 'http://localhost/biochem/wp-content/uploads//godzilla-article2.jpghttp://localhost/biochem/wp-content/uploads/life-goes-on-wpcf_300x111.jp';
array_slice(
array_map(
function($item) { return "http://" . $item;},
explode("http://", $test)),
1);
For answering this question by regular expression I think you want something like this:
$test = "http://localhost/biochem/wp-content/uploads//godzilla-article2.jpghttp://localhost/biochem/wp-content/uploads/life-goes-on-wpcf_300x111.jpg";
$keywords = preg_split("/.http:\/\//",$test);
print_r($keywords);
It returns exactly something you need:
Array
(
[0] => http://localhost/biochem/wp-content/uploads//godzilla-article2.jp
[1] => localhost/biochem/wp-content/uploads/life-goes-on-wpcf_300x111.jpg
)