PHP Turn a Numbered String List into Array - php

With PHP if you have a string which may or may not have spaces after the dot, such as:
"1. one 2.too 3. free 4. for 5.five "
What function can you use to create an array as follows:
array(1 => "one", 2 => "too", 3 => "free", 4 => "for", 5 => "five")
with the key being the list item number (e.g the array above has no 0)
I presume a regular expression is needed and perhaps use of preg_split or similar? I'm terrible at regular expressions so any help would be greatly appreciated.

What about:
$str = "1. one 2.too 3. free 4. for 5.five ";
$arr = preg_split('/\d+\./', $str, -1, PREG_SPLIT_NO_EMPTY);
print_r($arr);

I got a quick hack and it seems to be working fine for me
$string = "1. one 2.too 3. free 4. for 5.five ";
$text_only = preg_replace("/[^A-Z,a-z]/",".",$string);
$num_only = preg_replace("/[^0-9]/",".",$string);
$explode_nums = explode('.',$num_only);
$explode_text = explode('.',$text_only);
foreach($explode_text as $key => $value)
{
if($value !== '' && $value !== ' ')
{
$text_array[] = $value;
}
}
foreach($explode_nums as $key => $value)
{
if($value !== '' && $value !== ' ')
{
$num_array[] = $value;
}
}
foreach($num_array as $key => $value)
{
$new_array[$value] = $text_array[$key];
}
print_r($new_array);
Test it out and let me know if works fine

Related

Generate all possible matches for regex pattern in PHP

There are quite a few questions on SO asking about how to parse a regex pattern and output all possible matches to that pattern. For some reason, though, every single one of them I can find (1, 2, 3, 4, 5, 6, 7, probably more) are either for Java or some variety of C (and just one for JavaScript), and I currently need to do this in PHP.
I’ve Googled to my heart’s (dis)content, but whatever I do, pretty much the only thing that Google gives me is links to the docs for preg_match() and pages about how to use regex, which is the opposite of what I want here.
My regex patterns are all very simple and guaranteed to be finite; the only syntax used is:
[] for character classes
() for subgroups (capturing not required)
| (pipe) for alternative matches within subgroups
? for zero-or-one matches
So an example might be [ct]hun(k|der)(s|ed|ing)? to match all possible forms of the verbs chunk, thunk, chunder and thunder, for a total of sixteen permutations.
Ideally, there’d be a library or tool for PHP which will iterate through (finite) regex patterns and output all possible matches, all ready to go. Does anyone know if such a library/tool already exists?
If not, what is an optimised way to approach making one? This answer for JavaScript is the closest I’ve been able to find to something I should be able to adapt, but unfortunately I just can’t wrap my head around how it actually works, which makes adapting it more tricky. Plus there may well be better ways of doing it in PHP anyway. Some logical pointers as to how the task would best be broken down would be greatly appreciated.
Edit: Since apparently it wasn’t clear how this would look in practice, I am looking for something that will allow this type of input:
$possibleMatches = parseRegexPattern('[ct]hun(k|der)(s|ed|ing)?');
– and printing $possibleMatches should then give something like this (the order of the elements is not important in my case):
Array
(
[0] => chunk
[1] => thunk
[2] => chunks
[3] => thunks
[4] => chunked
[5] => thunked
[6] => chunking
[7] => thunking
[8] => chunder
[9] => thunder
[10] => chunders
[11] => thunders
[12] => chundered
[13] => thundered
[14] => chundering
[15] => thundering
)
Method
You need to strip out the variable patterns; you can use preg_match_all to do this
preg_match_all("/(\[\w+\]|\([\w|]+\))/", '[ct]hun(k|der)(s|ed|ing)?', $matches);
/* Regex:
/(\[\w+\]|\([\w|]+\))/
/ : Pattern delimiter
( : Start of capture group
\[\w+\] : Character class pattern
| : OR operator
\([\w|]+\) : Capture group pattern
) : End of capture group
/ : Pattern delimiter
*/
You can then expand the capture groups to letters or words (depending on type)
$array = str_split($cleanString, 1); // For a character class
$array = explode("|", $cleanString); // For a capture group
Recursively work your way through each $array
Code
function printMatches($pattern, $array, $matchPattern)
{
$currentArray = array_shift($array);
foreach ($currentArray as $option) {
$patternModified = preg_replace($matchPattern, $option, $pattern, 1);
if (!count($array)) {
echo $patternModified, PHP_EOL;
} else {
printMatches($patternModified, $array, $matchPattern);
}
}
}
function prepOptions($matches)
{
foreach ($matches as $match) {
$cleanString = preg_replace("/[\[\]\(\)\?]/", "", $match);
if ($match[0] === "[") {
$array = str_split($cleanString, 1);
} elseif ($match[0] === "(") {
$array = explode("|", $cleanString);
}
if ($match[-1] === "?") {
$array[] = "";
}
$possibilites[] = $array;
}
return $possibilites;
}
$regex = '[ct]hun(k|der)(s|ed|ing)?';
$matchPattern = "/(\[\w+\]|\([\w|]+\))\??/";
preg_match_all($matchPattern, $regex, $matches);
printMatches(
$regex,
prepOptions($matches[0]),
$matchPattern
);
Additional functionality
Expanding nested groups
In use you would put this before the "preg_match_all".
$regex = 'This happen(s|ed) to (be(come)?|hav(e|ing)) test case 1?';
echo preg_replace_callback("/(\(|\|)(\w+)(?:\(([\w\|]+)\)\??)/", function($array){
$output = explode("|", $array[3]);
if ($array[0][-1] === "?") {
$output[] = "";
}
foreach ($output as &$option) {
$option = $array[2] . $option;
}
return $array[1] . implode("|", $output);
}, $regex), PHP_EOL;
Output:
This happen(s|ed) to (become|be|have|having) test case 1?
Matching single letters
The bones of this would be to update the regex:
$matchPattern = "/(?:(\[\w+\]|\([\w|]+\))\??|(\w\?))/";
and add an else to the prepOptions function:
} else {
$array = [$cleanString];
}
Full working example
function printMatches($pattern, $array, $matchPattern)
{
$currentArray = array_shift($array);
foreach ($currentArray as $option) {
$patternModified = preg_replace($matchPattern, $option, $pattern, 1);
if (!count($array)) {
echo $patternModified, PHP_EOL;
} else {
printMatches($patternModified, $array, $matchPattern);
}
}
}
function prepOptions($matches)
{
foreach ($matches as $match) {
$cleanString = preg_replace("/[\[\]\(\)\?]/", "", $match);
if ($match[0] === "[") {
$array = str_split($cleanString, 1);
} elseif ($match[0] === "(") {
$array = explode("|", $cleanString);
} else {
$array = [$cleanString];
}
if ($match[-1] === "?") {
$array[] = "";
}
$possibilites[] = $array;
}
return $possibilites;
}
$regex = 'This happen(s|ed) to (be(come)?|hav(e|ing)) test case 1?';
$matchPattern = "/(?:(\[\w+\]|\([\w|]+\))\??|(\w\?))/";
$regex = preg_replace_callback("/(\(|\|)(\w+)(?:\(([\w\|]+)\)\??)/", function($array){
$output = explode("|", $array[3]);
if ($array[0][-1] === "?") {
$output[] = "";
}
foreach ($output as &$option) {
$option = $array[2] . $option;
}
return $array[1] . implode("|", $output);
}, $regex);
preg_match_all($matchPattern, $regex, $matches);
printMatches(
$regex,
prepOptions($matches[0]),
$matchPattern
);
Output:
This happens to become test case 1
This happens to become test case
This happens to be test case 1
This happens to be test case
This happens to have test case 1
This happens to have test case
This happens to having test case 1
This happens to having test case
This happened to become test case 1
This happened to become test case
This happened to be test case 1
This happened to be test case
This happened to have test case 1
This happened to have test case
This happened to having test case 1
This happened to having test case

PHP Compare integers

I have the following integers
7
77
0
20
in an array. I use them to check from where a call originated.
Numbers like 730010123, 772930013, 20391938.
What I need to do is I need a way to check if the number starts with 7 or 77 for an example.
Is there any way to do this in PHP and avoid a thousand if statements?
One issue I am having is that if I check if the number starts with 7 the numbers that start with 77 are being called as well. Note that 7 numbers are mobile and 77 are shared cost numbers and not equal in any way so I need to separate them.
if (substr($str, 0, 1) == '7') ||{
if (substr($str, 0, 2) == '77'){
//starts with '77'
} else {
//starts with '7'
}
}
I made a little example with a demo array, I hope you can use it:
$array = array(
7 => 'Other',
70 => 'Fryslan!',
20 => 'New York',
21 => 'Dublin',
23 => 'Amsterdam',
);
$number = 70010123;
$place = null;
foreach($array as $possibleMatch => $value) {
if (preg_match('/^' . (string)$possibleMatch . '/', (string)$number))
$place = $value;
}
echo $place;
The answer in this case is "Fryslan". You have to remember that 7 also matches in this case? So you may want to add some metric system in case of two matches.
Is this you want?
<?php
$myarray = array(730010123, 772930013, 20391938);
foreach($myarray as $value){
if(substr($value, 0, 2) == "77"){
echo "Starting With 77: <br/>";
echo $value;
echo "<br>";
}
if((substr($value, 0, 1) == "7")&&(substr($value, 0, 2) != "77")){
echo "Starting With 7: <br/>";
echo $value;
echo "<br>";
}
}
?>
You could use preg_match and array_filter for that
function check_digit($var) {
return preg_match("/^(7|77|0)\d+$/");
}
$array_to_be_check = array("730010123" , "772930013", "20391938");
print_r(array_filter($array_to_be_check, "check_digit"));
A way to do this is to handle the "integer" you received as a number as being a string.
Doing so by something like this:
$number = 772939913;
$filter = array (
'77' => 'type1',
'20' => 'type2',
'7' => 'type3',
'0' => 'type4');
$match = null;
foreach ($filter as $key => $val){
$comp = substr($number, 0, strlen($key));
if ($comp == $key){
$match = $key;
break;
}
}
if ($match !== null){
echo 'the type is: ' . $filter[$match];
//you can proceed with your task
}

php remove the value from array

need help replacing array value
i`m trying check experience and space exists in the below array and replace space with experience max (i,e next array values if its equal null/space replace with experience max),
i have pasted code below which im using to find and replace array value, its replacing the experience to experience max instead of empty to experience max
array[1] => name,
array[2] => Work Experience,
array[3] => ,
array[4] => company,
array[5] => location
o/p :
array[1] => name,
array[2] => Work Experience,
array[3] => Work Experience Max,
array[4] => company,
array[5] => location
$search = "Work Experience";
foreach ($val as $key=> $cnt) {
// echo "inside foreach ".$cnt;
if ($cnt == $search) {
echo $keyvalue = $key;
break;
}
}
if (isset($keyvalue)) {
$firstarryval = array_splice($val, $keyvalue, 1);
}
if ($firstarryval == '') {
array_splice($val, $keyvalue, 0, "Work Experience Max");
} else {
array_splice($val, $keyvalue, 0, "Work Experience Max");
}
Ok, here is the solution explained:
$arr = array( 0=>'name', 1=>'Work Experience', 2=>'', 3=>'company', 4=>'location' );
var_export($arr); echo '<br/>';
$search = "Work Experience";
$arrkey = false;
foreach($arr as $key=>$value){ // set variables and advance internal pointer
echo "inside foreach $key => $value <br/>";
if( $value == $search ) {
echo $key;
echo $arrkey = key($arr); // internal php pointer already points to next array key
break;
}
}
if ($arrkey!=false && empty($arr[$arrkey])) {
$arr[$arrkey] = 'Work Experience Max';
}
echo '<br/>'; var_export($arr);
Useful links: foreach, key, empty. Hope it will help! :-)

Search for a part of an array and get the rest of it in PHP

I've got an array called $myarray with values like these:
myarray = array (
[0] => eat-breakfast
[1] => have-a-break
[2] => dance-tonight
[3] => sing-a-song
)
My goal is to search for a part of this array and get the rest of it. Here is an example:
If i submit eat, I would like to get breakfast.
If i submit have, I would like to get a-break.
I just try but I'm not sure at all how to do it...
$word = 'eat';
$pattern = '/'.$word.'/i';
foreach ($myarray as $key => $value) {
if(preg_match($pattern, $value, $matches)){
echo $value;
}
}
print_r($matches);
It displays:
eat-breakfastArray ( )
But I want something like that:
breakfast
I think I'm totally wrong, but I don't have any idea how to proceed.
Thanks.
use
stripos($word, $myarray)
<?php
$myarray = array (
'eat-breakfast',
'have-a-break',
'dance-tonight',
'sing-a-song'
) ;
function search($myarray, $word){
foreach($myarray as $index => $value){
if (stripos($value, $word) !== false){
echo str_replace(array($word,'-'), "", $value);
}
}
}
search($myarray, 'dance');
echo "<br />";
search($myarray, 'have-a');
echo "<br />";
search($myarray, 'sing-a');
demo
I think the word you seek is at the beginning. Try this
function f($myarray, $word)
{
$len = strlen($word);
foreach($myarray as $item)
{
if(substr($item, 0, $len) == $word)
return substr($item, $len+1);
}
return false;
}
You're feeding the wrong information into preg_match, although I'd recommend using array_search().. Check out my updated snippet:
$word = 'eat';
$pattern = '/'.$word.'/i';
foreach ($myarray as $key => $value) {
if(preg_match($pattern, $value, $matches)){
echo $value;
}
}
print_r($matches);
To get rid of that last bit, just perform a str_replace operation to replace the word with ""
This will both search the array (with a native function) and return the remainder of the string.
function returnOther($search, $array) {
$found_key = array_search($search, $array);
$new_string = str_replace($search . "-", "", $array[$found_key]);
return $new_string;
}

Help with PHP Array code

Hey guys!
I need some help writing a code that creates an array in the format I needed in. I have this long string of text like this -> "settings=2&options=3&color=3&action=save"...etc Now the next thing I did to make it into an array is the following:
$form_data = explode("&", $form_data);
Ok so far so good...I now have an array like so:
Array
(
[0] => settings=2
[1] => options=3
[2] => color=3
[3] => action=save
)
1
Ok now I need to know how to do two things. First, how can I remove all occurences of "action=save" from the array?
Second, how can I make this array become a key value pair (associative array)? Like "settings=>2"?
Thanks...
There's a function for that. :)
parse_str('settings=2&options=3&color=3&action=save', $arr);
if (isset($arr['action']) && $arr['action'] == 'save') {
unset($arr['action']);
}
print_r($arr);
But just for reference, you could do it manually like this:
$str = 'settings=2&options=3&color=3&action=save';
$arr = array();
foreach (explode('&', $str) as $part) {
list($key, $value) = explode('=', $part, 2);
if ($key == 'action' && $value == 'save') {
continue;
}
$arr[$key] = $value;
}
This is not quite equivalent to parse_str, since key[] keys wouldn't be parsed correctly. I'd be sufficient for your example though.
$str = 'settings=2&options=3&color=3&action=save&action=foo&bar=save';
parse_str($str, $array);
$key = array_search('save', $array);
if($key == 'action') {
unset($array['action']);
}
Ideone Link
This could help on the parsing your array, into key/values
$array; // your array here
$new_array = array();
foreach($array as $key)
{
$val = explode('=',$key);
// could also unset($array['action']) if that's a global index you want removed
// if so, no need to use the if/statement below -
// just the setting of the new_array
if(($val[0] != 'action' && $val[1] != 'save'))$new_array[] = array($val[0]=>$val[1]);
}

Categories