get values using regular expression and preg_match_all - php

I have string data
$pages = "mangaName=&authorArtist=asdas123s&genres=sn&genres[23]=on&genres[29]=on&status=&chrome=&submit=+";
function get_h1($file){
$h1tags = preg_match_all('/\[(\w*)\]/is',$file,$patterns);
$res = array();
array_push($res,$patterns[2]);
array_push($res,count($patterns[2]));
return $res;
}
i want get number on genres[23] , genres[29]
[0] => 23
[1] => 29

$pages = "mangaName=&authorArtist=asdas123s&genres=sn&genres[23]=on&genres[29]=on&status=&chrome=&submit=+";
parse_str($pages, $parsed);
var_dump(array_keys($parsed['genres'])); // array(2) { [0]=> int(23) [1]=> int(29) }

zerkms' answer is the right one, but if you really want to use regexp, change yours with this one:
preg_match_all('/\[(\w*?)\]/is',$file,$patterns);
note the non-greedy __^

Related

PHP : How to select specific parts of a string [duplicate]

This question already has answers here:
Extract a substring between two characters in a string PHP
(11 answers)
Closed 10 months ago.
I was wondering... I have two strings :
"CN=CMPPDepartemental_Direction,OU=1 - Groupes de sécurité,OU=CMPP_Departementale,OU=Pole_Ambulatoire,OU=Utilisateurs_ADEI,DC=doadei,DC=wan",
"CN=CMPPDepartemental_Secretariat,OU=1 - Groupes de sécurité,OU=CMPP_Departementale,OU=Pole_Ambulatoire,OU=Utilisateurs_ADEI,DC=doadei,DC=wan"
Is there a way in php to select only the first part of these strings ? I would like to just select CMPPDepartemental_Direction and CMPPDepartemental_Secretariat.
I had thought of trying with substr() or trim() but without success.
You should use preg_match with regex CN=(\w+_\w+) to extract needed parts:
$strs = [
"CN=CMPPDepartemental_Direction,OU=1 - Groupes de sécurité,OU=CMPP_Departementale,OU=Pole_Ambulatoire,OU=Utilisateurs_ADEI,DC=doadei,DC=wan",
"CN=CMPPDepartemental_Secretariat,OU=1 - Groupes de sécurité,OU=CMPP_Departementale,OU=Pole_Ambulatoire,OU=Utilisateurs_ADEI,DC=doadei,DC=wan"
];
foreach ($strs as $str) {
$matches = null;
preg_match('/CN=(\w+_\w+)/', $str, $matches);
echo $matches[1];
}
If the strings always have the same structure, I recommend using a custom function find_by_keyword - so you can search for other keywords too.
function find_by_keyword( $string, $keyword ) {
$array = explode(",",$string);
$found = [];
// Loop through each item and check for a match.
foreach ( $array as $string ) {
// If found somewhere inside the string, add.
if ( strpos( $string, $keyword ) !== false ) {
$found[] = substr($string, strlen($keyword));
}
}
return $found;
}
var_dump(find_by_keyword($str2, "CN="));
// array(1) {
[0]=>
string(27) "CMPPDepartemental_Direction"
}
var_dump(find_by_keyword($str2, "OU="));
//array(4) {
[0]=>
string(25) "1 - Groupes de sécurité"
[1]=>
string(4) "CMPP"
[2]=>
string(4) "Pole"
[3]=>
string(12) "Utilisateurs"
}
Examle here.

Get VALUES from url in PHP

I need to get ID´s from url:
http://www.aaaaa/galery.php?position=kosice&kategory=Castles&ID=1&ID=5&ID=24&ID=32
If i use $_GET['ID'] a still get only last ID value. I need to get all of them to array, or select.
Can anybody help me?
Use array syntax:
http://www.aaaaa/galery.php?position=kosice&kategory=Castles&ID[]=1&ID[]=5&ID[]=24&ID[]=32
var_dump($_GET['ID']);
array(4) {
[0]=>
int(1)
[1]=>
int(5)
[2]=>
int(24)
[3]=>
int(32)
}
}
echo $_GET['ID'][2]; // 24
The format in the URL is wrong. The second "ID" is overwriting the first "ID".. use an array:
http://www.example.org/?id[]=1&id[]=2&id[]=3
In PHP:
echo $_GET['id'][0]; // 1
echo $_GET['id'][1]; // 2
echo $_GET['id'][2]; // 3
To get this you need to make ID as array and pass it in the URL
http://www.aaaaa/galery.php?position=kosice&kategory=Castles&ID[]=1&ID[]=5&ID[]=24&ID[]=32
and this can be manipulated at the backend like this
$urls = $_GET['ID'];
foreach($urls as $url){
echo $url;
}
OR
An alternative would be to pass json encoded arrays
http://www.aaaaa/galery.php?position=kosice&kategory=Castles&ID=[1,2,24,32]
which can be used as
$myarr = json_decode($_GET['ID']); // array(1,2,24,32)
I recommend you to also see for this here.
http_build_query()
it's wrong but if you really want to do this
<?php
function getIds($string){
$string = preg_match_all("/[ID]+[=]+[0-9]/i", $string, $matches);
$ids = [];
foreach($matches[0] as $match)
{
$c = explode("=", $match);
$ids [] = $c[1];
}
return $ids;
}
// you can change this with $_SERVER['QUERY_STRING']
$url = "http://www.aaaaa/galery.php?position=kosice&kategory=Castles&ID=1&ID=5&ID=24&ID=32";
$ids = getIds($url);
var_dump($ids);

How do I check to see if array slot is empty?

In the example below $list is an array created by user input earlier in the code, and some slots the user has input nothing. I want to skip the empty items, so the commas aren't created in the output.
$list = array("first", "second", "", "", "fifth", "sixth", "", "");
foreach ($list as $each){$places .= $each . ",";}
results
first,second,,,fifth,sixth,,,
result I want
first,second,fifth,sixth
Got a solution. It looks like this:
$list = array_filter($list);
$places .= implode (",",$list);
To ignore the empty values, you can use
$list = array_filter($list);
Results
Array
(
[0] => first
[1] => second
[4] => fifth
[5] => sixth
)
Source: Mark
array_filter, when passed no second parameter, will remove any empty entries. From there you can proceed as normal:
foreach (array_filter($list) as $each){
$places .= $each . ',';
}
Though you can also use implode if you're just turning it in to a CSV:
$places .= implode(',', array_filter($list));
Side Note Though in this case array_filter may work, it is worth noting that this removes entries that result in a "falsy" result. That is to say:
$list = array_filter(array('foo','0','false',''));
// Result:
// array(2) {
// [0]=>
// string(3) "foo"
// [2]=>
// string(5) "false"
// }
So be careful. If the user could potentially be entering in numbers, I would stick with comparing empty. Alternatively you can use the second parameter of array_filter to make it more explicit:
function nonEmptyEntries($e)
{
return ((string)$e) !== '';
}
$list = array_filter($list, 'nonEmptyEntries');
// result:
//array(3) {
// [0]=>
// string(3) "foo"
// [1]=>
// string(1) "0"
// [2]=>
// string(5) "false"
//}
(Note that the 0 entry is kept, which differs from a blanket array_filter)

Split long string into little ones. - trying to find an elegant way for doing so

If the string is bigger then 50 chars long, I need to split it.
The maximum allowed is 3 chunks of 50. It could be less then 50 but never more then 150.
I don't need any special chars to be added, or to serve as "splitters"; I can break the string anywhere, no problem, since the propose is not for showing it to the user.
if (strlen($street) > 50)
{
$streetPart1 = substr($street,0,50);
$streetPart2 = substr($street,51,100);
$streetPart3 = substr($street,101,150);
}
Is there a more elegant way for doing this?
UPDATE:
An example of what would arrive next:
if (strlen($street) > 50)
{
$streetPart1 = substr($street,0,50);
$streetPart2 = substr($street,51,100);
$streetPart3 = substr($street,101,150);
if(!empty($streetPart2) && empty($streetPart3)
{
//add part2 only.
}elseif(!empty($streetPart2 && !empty($streetPart3))
{
//add part 2 and part 3
}
}
Thanks a lot.
MEM
You may simply use str_split:
$parts = str_split($string, 50);
// if you want to have vars instead of array:
list($part1, $part2, $part3) = str_split($string, 50);
Check the PHP's wordwrap() function.
http://php.net/manual/en/function.wordwrap.php
And check out the explode() function
http://php.net/manual/en/function.explode.php
<?
function wrapAndCropToArray($text, $width, $lines)
{
$ret = array_slice(
explode("\n",wordwrap($text,$width,"\n",true))
, 0
, $lines+1
);
if(isset($ret[$lines]))
$ret[$lines] = "...";
return $ret;
}
$test = "aadfuiosdy 34 123 412 341f2 38947 1029 384h120 39uh4 19023h 41234";
var_dump(wrapAndCropToArray($test,10,3));
?>
Will output:
array(4) {
[0]=>
string(10) "aadfuiosdy"
[1]=>
string(10) "34 123 412"
[2]=>
string(5) "341f2"
[3]=>
string(3) "..."
}

php pushing pattern from array1 to array2

I have an array that looks something like this
array(7) {
[0]=> "hello,pat1"
[1]=> "hello,pat1"
[2]=> "test,pat2"
[3]=> "test,pat2"
[4]=> "foo,pat3"
[5]=> "foo,pat3"
[6]=> "foo,pat3"
....
}
I would like to push it into another array so the output of the array2 is as follow:
array(7) {
[0]=> "hello,pat1"
[1]=> "test,pat2"
[2]=> "foo,pat3"
[3]=> "foo,pat3"
[4]=> "foo,pat3"
[5]=> "hello,pat1"
[6]=> "test,pat2"
.....
}
What I want is to push them in the following pattern: 1 "pat1" 1 "pat2" and 3 "pat3", and repeat this pattern every 5 elements.
while ( !empty( $array1 ) )
$a = explode(",",$array1[$i]);
if($a[1]=='pat1' &&)
push && unset
elseif($a[1]=='pat2' &&)
push && unset
elseif($a[1]=='pat3' and < 5)
push && unset and reset pattern counter
}
What would be a good way of doing this?
Any idea will be appreciate it.
Time for some fun with the iterators of the Standard PHP Library :-)
<?php
$array1 = array (
"hello1,pat1", "hello2,pat1", "hello3,pat1",
"test1,pat2", "test2,pat2",
"foo1,pat3", "foo2,pat3", "foo3,pat3",
"foo4,pat3", "foo5,pat3", "foo6,pat3"
);
// "group by" patN
$foo = array();
foreach($array1 as $a) {
// feel free to complain about the # here ...to somebody else
#$foo[ strrchr($a, ',') ][] = $a;
}
// split pat3 into chunks of 3
$foo[',pat3'] = array_chunk($foo[',pat3'], 3);
// add all "groups" to a MultipleIterator
$mi = new MultipleIterator(MultipleIterator::MIT_NEED_ANY);
foreach($foo as $x) {
$mi->attachIterator( new ArrayIterator($x) );
}
// each call to $mi->current() will return an array
// with the current items of all registered iterators
foreach ($mi as $x) {
// "flatten" the nested arrays
foreach( new RecursiveIteratorIterator(new RecursiveArrayIterator($x)) as $e) {
echo $e, "\n";
}
echo "----\n";
}
I think I'd set respective counters with respective incrementation. Since php will cast float keys to integers, you can just increment the ,pat3 items with .33 instead of 1. Then, to flatten the result, just use array_merge() with the splat operator.
Code: (Demo)
$array = [
"hello1,pat1",
"hello2,pat1",
"test3,pat2",
"test4,pat2",
"foo5,pat3",
"foo6,pat3",
"foo7,pat3",
];
$counters = [',pat1' => 0, ',pat2' => 0, ',pat3' => 0];
foreach ($array as $value) {
$end = strrchr($value, ',');
$groups[$counters[$end]][] = $value;
$counters[$end] += ($end === ',pat3' ? .33 : 1);
}
var_export(array_merge(...$groups));
Output:
array (
0 => 'hello1,pat1',
1 => 'test3,pat2',
2 => 'foo5,pat3',
3 => 'foo6,pat3',
4 => 'foo7,pat3',
5 => 'hello2,pat1',
6 => 'test4,pat2',
)

Categories