PHP array remove characters and keep only the numbers - php

looking for the code can remove characters from the array and display numbers only.
array(
1=>123456 hello; / &,
2=>128767 ^% * ! ajsdb,
3=>765678 </ hello echo.,
);
i want to remove the floowing from the array
hello; / &
^% * ! ajsdb
</ hello echo.
and wants to keep as stated
array(
1=>123456,
2=>128767,
3=>765678,
);
Thanks and Kind Regards,

You want to use preg_replace to replace all non-numeric chars with ''
$arr = array(
1 => "1234 perr & *",
2 => "3456 hsdsd 3434"
);
foreach($arr as &$item) {
$item = preg_replace('/\D/', '', $item);
}
var_dump($arr);
results in
array(2) { [1]=> string(4) "1234" [2]=> &string(8) "34563434" }

Make a for statement to get values of your array and try this:
foreach($arr as $value){
$cleansedstring = remove_non_numeric($value);
echo $cleansedstring;
}
function remove_non_numeric($string) {
return preg_replace('/\D/', '', $string)
}

<?php
// Set array
$array = array(
1 => "123456 hello; / &",
2 => "128767 ^% * ! ajsdb",
3 => "765678 </ hello echo.",
);
// Loop through $array
foreach($array as $key => $item){
// Set $array[$key] to value of $item with non-numeric values removed
// (Setting $item will not change $array, so $array[$key] is set instead)
$array[$key] = preg_replace('/[^0-9]+/', '', $item);
}
// Check results
print_r($array);
?>

function number_only($str){
$slength = strlen($str);
$returnVal = null;
for($i=0;$i<$slength;$i++){
if(is_numeric($str[$i])){
$returnVal .=$str[$i];
}
}
return $returnVal;
}

You should use preg_replace using [0-9]+

like this
$values = array(
1=>"123456 hello; / &",
2=>"128767 ^% * ! ajsdb",
3=>"765678 </ hello echo",
);
$number_values = array();
foreach($values as $value) {
$pieces = explode(' ', $value);
$numbers = array_filter($pieces, function($value) {
return is_numeric($value);
});
if(count($numbers) > 0)
{
$number_values[] = current($numbers);
}
}
print_r($number_values);

I would advice you to take a look at the intval method (http://php.net/manual/en/function.intval.php) and the foreach loop (http://php.net/manual/en/control-structures.foreach.php).
With those 2 functions combined you will be able to clear all the elements from the not numeric characters,

Why not array_walk() ? http://php.net/manual/en/function.array-walk.php
$arr = array(
1 => "1234 perr & *",
2 => "3456 hsdsd 3434"
);
array_walk($arr, function(&$item) {
$item = preg_replace('/\D/', '', $item);
});
print_r($arr);
Result:
Array
(
[1] => 1234
[2] => 34563434
)
Check it online:
http://sandbox.onlinephpfunctions.com/code/d63d07e58f9ed6984f96eb0075955c7b36509f81

Related

explode string to multidimensional with regular expression

I have string like this
$string = 'title,id,user(name,email)';
and I want result to be like this
Array
(
[0] => title
[1] => id
[user] => Array
(
[0] => name
[1] => email
)
)
so far I tried with explode function and multiple for loop the code getting ugly and i think there must be better solution by using regular expression like preg_split.
Replace the comma with ### of nested dataset then explode by a comma. Then make an iteration on the array to split nested dataset to an array. Example:
$string = 'user(name,email),office(title),title,id';
$string = preg_replace_callback("|\(([a-z,]+)\)|i", function($s) {
return str_replace(",", "###", $s[0]);
}, $string);
$data = explode(',', $string);
$data = array_reduce($data, function($old, $new) {
preg_match('/(.+)\((.+)\)/', $new, $m);
if(isset($m[1], $m[2]))
{
return $old + [$m[1] => explode('###', $m[2])];
}
return array_merge($old , [$new]);
}, []);
print '<pre>';
print_r($data);
First thanks #janie for enlighten me, I've busied for while and since yesterday I've learnt a bit regular expression and try to modify #janie answer to suite with my need, here are my code.
$string = 'user(name,email),title,id,office(title),user(name,email),title';
$commaBetweenParentheses = "|,(?=[^\(]*\))|";
$string = preg_replace($commaBetweenParentheses, '###', $string);
$array = explode(',', $string);
$stringFollowedByParentheses = '|(.+)\((.+)\)|';
$final = array();
foreach ($array as $value) {
preg_match($stringFollowedByParentheses, $value, $result);
if(!empty($result))
{
$final[$result[1]] = explode('###', $result[2]);
}
if(empty($result) && !in_array($value, $final)){
$final[] = $value;
}
}
echo "<pre>";
print_r($final);

replace all keys in php array

This is my array:
['apple']['some code']
['beta']['other code']
['cat']['other code 2 ']
how can I replace all the "e" letters with "!" in the key name and keep the values
so that I will get something like that
['appl!']['some code']
['b!ta']['other code']
['cat']['other code 2 ']
I found this but because I don't have the same name for all keys I can't use It
$tags = array_map(function($tag) {
return array(
'name' => $tag['name'],
'value' => $tag['url']
);
}, $tags);
I hope your array looks like this:-
Array
(
[apple] => some code
[beta] => other code
[cat] => other code 2
)
If yes then you can do it like below:-
$next_array = array();
foreach ($array as $key=>$val){
$next_array[str_replace('e','!',$key)] = $val;
}
echo "<pre/>";print_r($next_array);
output:- https://eval.in/780144
You can stick with array_map actually. It is not really practical, but as a prove of concept, this can be done like this:
$array = array_combine(
array_map(function ($key) {
return str_replace('e', '!', $key);
}, array_keys($array)),
$array
);
We use array_keys function to extract keys and feed them to array_map. Then we use array_combine to put keys back to place.
Here is working demo.
Here we are using array_walk and through out the iteration we are replacing e to ! in key and putting the key and value in a new array.
Try this code snippet here
<?php
$firstArray = array('apple'=>'some code','beta'=>'other code','cat'=>'other code 2 ');
$result=array();
array_walk($firstArray, function($value,$key) use (&$result) {
$result[str_replace("e", "!", $key)]=$value;
});
print_r($result);
If you got this :
$firstArray = array('apple'=>'some code','beta'=>'other code','cat'=>'other code 2 ');
You can try this :
$keys = array_keys($firstArray);
$outputArray = array();
$length = count($firstArray);
for($i = 0; $i < $length; $i++)
{
$key = str_replace("e", "!", $keys[ $i ]);
$outputArray[ $key ] = $firstArray[$keys[$i]];
}
We can iterate the array and mark all problematic keys to be changed. Check for the value whether it is string and if so, make sure the replacement is done if needed. If it is an array instead of a string, then call the function recursively for the inner array. When the values are resolved, do the key replacements and remove the bad keys. In your case pass "e" for $old and "!" for $new. (untested)
function replaceKeyValue(&$arr, $old, $new) {
$itemsToRemove = array();
$itemsToAdd = array();
foreach($arr as $key => $value) {
if (strpos($key, $old) !== false) {
$itemsToRemove[]=$key;
$itemsToAdd[]=str_replace($old,$new,$key);
}
if (is_string($value)) {
if (strpos($value, $old) !== false) {
$arr[$key] = str_replace($old, $new, $value);
}
} else if (is_array($value)) {
$arr[$key] = replaceKeyValue($arr[$key], $old, $new);
}
}
for ($index = 0; $index < count($itemsToRemove); $index++) {
$arr[$itemsToAdd[$index]] = $itemsToRemove[$index];
unset($arr[$itemsToRemove[$index]]);
}
return $arr;
}
Another option using just 2 lines of code:
Given:
$array
(
[apple] => some code
[beta] => other code
[cat] => other code 2
)
Do:
$replacedKeys = str_replace('e', '!', array_keys($array));
return array_combine($replacedKeys, $array);
Explanation:
str_replace can take an array and perform the replace on each entry. So..
array_keys will pull out the keys (https://www.php.net/manual/en/function.array-keys.php)
str_replace will perform the replacements (https://www.php.net/manual/en/function.str-replace.php)
array_combine will rebuild the array using the keys from the newly updated keys with the values from the original array (https://www.php.net/manual/en/function.array-combine.php)

Regex hash and colons

I want to use regular expression to filter substrings from this string
eg: hello world #level:basic #lang:java:php #...
I am trying to produce an array with a structure like this:
Array
(
[0]=> hello world
[1]=> Array
(
[0]=> level
[1]=> basic
)
[2]=> Array
(
[0]=> lang
[1]=> java
[2]=> php
)
)
I have tried preg_match("/(.*)#(.*)[:(.*)]*/", $input_line, $output_array);
and what I have got is:
Array
(
[0] => hello world #level:basic #lang:java:php
[1] => hello world #level:basic
[2] => lang:java:php
)
In this case then I will have to apply this regex few times to the indexes and then apply a regex to filter the colon out. My question is: is it possible to create a better regex to do all in one go? what would the regex be? Thanks
You can use :
$array = explode("#", "hello world #level:basic #lang:java:php");
foreach($array as $k => &$v) {
$v = strpos($v, ":") === false ? $v : explode(":", $v);
}
print_r($array);
do this
$array = array() ;
$text = "hello world #level:basic #lang:java:php";
$array = explode("#", $text);
foreach($array as $i => $value){
$array[$i] = explode(":", trim($value));
}
print_r($array);
Got something for you:
Rules:
a tag begins with #
a tag may not contain whitespace/newline
a tag is preceeded and followed by whitespace or line beginning/ending
a tag can have several parts divided by :
Example:
#this:tag:matches this is some text #a-tag this is no tag: \#escaped
and this one tag#does:not:match
Function:
<?php
function parseTags($string)
{
static $tag_regex = '#(?<=\s|^)#([^\:\s]+)(?:\:([^\s]+))*(?=\s|$)#m';
$results = array();
preg_match_all($tag_regex, $string, $results, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
$tags = array();
foreach($results as $result) {
$tag = array(
'offset' => $result[0][1],
'raw' => $result[0][0],
'length' => strlen($result[0][0]),
0 => $result[1][0]);
if(isset($result[2]))
$tag = array_merge($tag, explode(':', $result[2][0]));
$tag['elements'] = count($tag)-3;
$tags[] = $tag;
}
return $tags;
}
?>
Result:
array(2) {
[0]=>array(7) {
["offset"]=>int(0)
["raw"]=>string(17) "#this:tag:matches"
["length"]=>int(17)
[0]=>string(4) "this"
[1]=>string(3) "tag"
[2]=>string(7) "matches"
["elements"]=>int(3)
}
[1]=>array(5) {
["offset"]=>int(36)
["raw"]=>string(6) "#a-tag"
["length"]=>int(6)
[0]=>string(5) "a-tag"
["elements"]=>int(1)
}
}
Each matched tag contains
the raw tag text
the tag offset and original length (e.g. to replace it in the string later with str... functions)
the number of elements (to safely iterate for($i = 0; $i < $tag['elements']; $i++))
This might work for you:
$results = array() ;
$text = "hello world #level:basic #lang:java:php" ;
$parts = explode("#", $text);
foreach($parts as $part){
$results[] = explode(":", $part);
}
var_dump($results);
Two ways using regex, note that you somehow need explode() since PCRE for PHP doesn't support capturing a subgroup:
$string = 'hello world #level:basic #lang:java:php';
preg_match_all('/(?<=#)[\w:]+/', $string, $m);
foreach($m[0] as $v){
$example1[] = explode(':', $v);
}
print_r($example1);
// This one needs PHP 5.3+
$example2 = array();
preg_replace_callback('/(?<=#)[\w:]+/', function($m)use(&$example2){
$example2[] = explode(':', $m[0]);
}, $string);
print_r($example2);
This give you the array structure you are looking for:
<pre><?php
$subject = 'hello world #level:basic #lang:java:php';
$array = explode('#', $subject);
foreach($array as &$value) {
$items = explode(':', trim($value));
if (sizeof($items)>1) $value = $items;
}
print_r($array);
But if you prefer you can use this abomination:
$subject = 'hello world #level:basic #lang:java:php';
$pattern = '~(?:^| ?+#)|(?:\G([^#:]+?)(?=:| #|$)|:)+~';
preg_match_all($pattern, $subject, $matches);
array_shift($matches[1]);
$lastKey = sizeof($matches[1])-1;
foreach ($matches[1] as $key=>$match) {
if (!empty($match)) $temp[]=$match;
if (empty($match) || $key==$lastKey) {
$result[] = (sizeof($temp)>1) ? $temp : $temp[0];
unset($temp);
}
}
print_r($result);

Get specific values from PHP Array

I'd like to get some values out of an array and print them out on the page.
For [1], these things should be extracted: USD 7.0269 6.4119 0.14231 0.15596
The array looks like this:
print_r($arr);
[1] => USD United States of America 7.0269 6.4119 Dollars 0.14231 0.15596 � Copyright 2003-2011. Powered by CurrencyXchanger 3.580
[2] => EUR Euro Member Countries 9.0373 8.3253 Euro 0.1107 0.1201 � Copyright 2003-2011. Powered by CurrencyXchanger 3.580
What is the best solution to accomplish this?
I'd use preg_match_all() after I trim off the area of interest:
foreach ($arr as $line) {
// currency is in the first four characters (apparently)
$currency = substr($line, 0, 4);
// we use everything left of 'Copyright'
$rest = strstr($line, 'Copyright', true);
// match each occurrence of nn.nnnn
if (preg_match_all('/\d+\.\d+/', $rest, $matches)) {
// $matches[0] contains all the amounts
echo $currency, ' ', join(' ', $matches[0]), PHP_EOL;
}
}
For PHP < 5.2 you need this line to calculate $rest:
$rest = substr($line, 0, strpos($line, 'Copyright'));
Demo
Here is a regex solution:
foreach($arr as $key => $item)
{
preg_match('/^([A-Z]){3}[\sA-Za-z]+(\d+\.\d+)\s+(\d+\.\d+)\s+[A-Za-z]+\s+(\d+\.\d+)\s+(\d+\.\d+)/', $item, $matches);
$result[$key] = array_shift($matches);
}
The regex corresponds to your pattern and captures everything you want inside consecutive elements of $matches. Since $matches[0] represents the full match, we remove the first element and assign it to your result array.
Try
foreach($arr as $v) {
$items = explode(' ', $v);
$new_arr[] = $items[0]; //Getting the currency type
foreach($items as $k => $m) {
if(is_numeric($m) && floor($m) != $m && $k != (count($items) - 1))
$new_arr[] = $m;
}
}
//displaying the $new_arr
foreach($new_arr as $n) {
if(is_numeric($n) === FALSE)
echo "\n";
echo $n . ' ';
}
See it in action here
Done quickly:
$result = array_map(
function ($string) {
preg_match_all('/(\d+\.\d+)\s/', $string, $matches);
return substr($string, 0, 3) . ' ' . implode(' ', $matches[1]);
},
$arr
);
Result:
Array
(
[0] => USD 7.0269 6.4119 0.14231 0.15596
[1] => EUR 9.0373 8.3253 0.1107 0.1201
)
With Regular Expressions you can get it.
foreach($arr as $key => $value) {
preg_match_all('/(\d+\.\d+)/', $value, $matches);
$result[substr($value, 0, 3)] = array_shift($matches);
}
You get an Array like this
var_dump($result);
array (
'USD' => array( 7.0269, 6.4119, 0.14231, 0.15596 )
'EUR' => array( 9.0373, 8.3253, 0.1107, 0.1201 )
)

PHP Turn a Numbered String List into Array

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

Categories