separate a text into numbers and letters using php - php

using php
I'm having a problem , I wanna read a text and separate it in numbers and letters
for example I wanna read this text: 4FS+2d,14 and get this output:'4' 'FS' '+' '2' 'd' ',' '14'
any idea how to do that?
thanks

Just use preg_match_all.
$string = '4FS+2d,14';
preg_match_all('/[0-9]+|[a-zA-Z]+|[^0-9a-zA-Z]+/', $string, $matches);
// ^ digits
// ^ chars
// ^ not digits, not chars
echo json_encode($matches); // json_encode for readability
// [["4","FS","+","2","d",",","14"]]
[0-9]+|[a-zA-Z]+|[^0-9a-zA-Z]+
Debuggex Demo

$str = '4FS+2d,14';
$arr = preg_split('#([\W]+|[\d]+)#i', $str, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
print_r($arr);
exit;
// output
Array
(
[0] => 4
[1] => FS
[2] => +
[3] => 2
[4] => d
[5] => ,
[6] => 14
)

Try like this:
<?php
$str = "4FS+2d,14";
for($loop=0;$loop<strlen($str);$loop++) {
$len[] = $str[$loop];
}
print_r($len);
?>
demo link: http://phpfiddle.org/main/code/de8-4yp

Related

Most elegant way to clean a string into only comma separated numerals

After instructing clients to input only
number comma number comma number
(no set length, but generally < 10), the results of their input have been, erm, unpredictable.
Given the following example input:
3,6 ,bannana,5,,*,
How could I most simply, and reliably end up with:
3,6,5
So far I am trying a combination:
$test= trim($test,","); //Remove any leading or trailing commas
$test= preg_replace('/\s+/', '', $test);; //Remove any whitespace
$test= preg_replace("/[^0-9]/", ",", $test); //Replace any non-number with a comma
But before I keep throwing things at it...is there an elegant way, probably from a regex boffin!
In a purely abstract sense this is what I'd do:
$test = array_filter(array_map('trim',explode(",",$test)),'is_numeric')
Example:
http://sandbox.onlinephpfunctions.com/code/753f4a833e8ff07cd9c7bd780708f7aafd20d01d
<?php
$str = '3,6 ,bannana,5,,*,';
$str = explode(',', $str);
$newArray = array_map(function($val){
return is_numeric(trim($val)) ? trim($val) : '';
}, $str);
print_r(array_filter($newArray)); // <-- this will give you array
echo implode(',',array_filter($newArray)); // <--- this give you string
?>
Here's an example using regex,
$string = '3,6 ,bannana,5,-6,*,';
preg_match_all('#(-?[0-9]+)#',$string,$matches);
print_r($matches);
will output
Array
(
[0] => Array
(
[0] => 3
[1] => 6
[2] => 5
[3] => -6
)
[1] => Array
(
[0] => 3
[1] => 6
[2] => 5
[3] => -6
)
)
Use $matches[0] and you should be on your way.
If you don't need negative numbers just remove the first bit in the in the regex rule.

How to split negative and positive values in string using php?

I have a string variable in php, with look like "0+1.65+0.002-23.9", and I want to split in their individual values.
Ex:
0
1.65
0.002
-23.9
I Try to do with:
$keys = preg_split("/^[+-]?\\d+(\\.\\d+)?$/", $data);
but not work I expected.
Can anyone help me out? Thanks a lot in advance.
Like this:
$yourstring = "0+1.65+0.002-23.9";
$regex = '~\+|(?=-)~';
$splits = preg_split($regex, $yourstring);
print_r($splits);
Output (see live php demo):
[0] => 0
[1] => 1.65
[2] => 0.002
[3] => -23.9
Explanation
Our regex is +|(?=-). We will split on whatever it matches
It matches +, OR |...
the lookahead (?=-) matches a position where the next character is a -, allowing us to keep the -
Then we split!
Option 2 if you decide you also want to keep the + Character
(?=[+-])
This regex is one lookahead that asserts that the next position is either a plus or a minus. For my sense of esthetics it's quite a nice solution to look at. :)
Output (see online demo):
[0] => 0
[1] => +1.65
[2] => +0.002
[3] => -23.9
Reference
Lookahead and Lookbehind Zero-Length Assertions
Mastering Lookahead and Lookbehind
You could try this
$data = ' 0 1.65 0.002 -23.9';
$t = str_replace( array(' ', ' -'), array(',',',-'), trim($data) );
$ta = explode(',', $t);
print_r($ta);
Which gives you an array containing each field like so:
Array
(
[0] => 0
[1] => 1.65
[2] => 0.002
[3] => -23.9
)
RE: Your comment: The originals values are in a string variable only separated for a sign possitive or negative
$data = ' 0+1.65+0.002-23.9 ';
$t = str_replace( array('-', '+'), array(',-',',+'), trim($data) );
$ta = explode(',', $t);
print_r($ta);
which gives a similiar answer but with the correct inputs and outputs
Array
(
[0] => 0
[1] => +1.65
[2] => +0.002
[3] => -23.9
)

Split sentence into words

for example i have sentenes like this:
$text = "word, word w.d. word!..";
I need array like this
Array
(
[0] => word
[1] => word
[2] => w.d
[3] => word".
)
I am very new for regular expression..
Here is what I tried:
function divide_a_sentence_into_words($text){
return preg_split('/(?<=[\s])(?<!f\s)\s+/ix', $text, -1, PREG_SPLIT_NO_EMPTY);
}
this
$text = "word word, w.d. word!..";
$split = preg_split("/[^\w]*([\s]+[^\w]*|$)/", $text, -1, PREG_SPLIT_NO_EMPTY);
print_r($split);
works, but i have second question i want to write list in mu regular exppression
"w.d" is special case.. for example this words is my list "w.d" , "mr.", "dr."
if i will take text:
$text = "word, dr. word w.d. word!..";
i need array:
Array (
[0] => word
[1] => dr.
[2] => word
[3] => w.d
[4] => word
)
sorry for bad english...
Using preg_split with a regex of /[^\w]*([\s]+[^\w]*|$)/ should work fine:
<?php
$text = "word word w.d. word!..";
$split = preg_split("/[^\w]*([\s]+[^\w]*|$)/", $text, -1, PREG_SPLIT_NO_EMPTY);
print_r($split);
?>
DEMO
Output:
Array
(
[0] => word
[1] => word
[2] => w.d
[3] => word
)
Use the function explode, that will split the string into an array
$words = explode(" ", $text);
use
str_word_count ( string $string [, int $format = 0 [, string $charlist ]] )
see here http://php.net/manual/en/function.str-word-count.php
it does exactly what you want. So in your case :
$myarray = str_word_count ($text,1);

Php split a string escaping quotas

I need to manage escaping in a comma split.
This is a string example:
var1,t3st,ax_1,c5\,3,last
I need this split:
var1
t3st
ax_1
c5\,3
last
Please mind this: "c5\,3" is not splitted.
I tried with this:
$expl=preg_split('#[^\\],#', $text);
But i loose the last char of each split.
use this regex
$str = 'var1,t3st,ax_1,c5\,3,last';
$expl=preg_split('#(?<!\\\),#', $str);
print_r($expl); // output Array ( [0] => var1 [1] => t3st [2] => ax_1 [3] => c5\,3 [4] => last )
working example http://codepad.viper-7.com/pWSu3S
Try with a lookbehind:
preg_split('#(?<!\\),#', $text);
Do a 3 phase approach
First replace \, with someting "unique" like \\
Do your split by ","
Replace \\ with \,
That not as nice as regex but it will work ;)
is this ok ?
<?php
$text = "var1,t3st,ax_1,c5\,3,last";
$text = str_replace("\,", "#", $text);
$xpode = explode(",", $text);
$new_text = str_replace("#", "\,", $xpode);
print_r($new_text);
?>
Output
Array ( [0] => var1 [1] => t3st [2] => ax_1 [3] => c5\,3 [4] => last )

PHP: Split string into array, like explode with no delimiter

I have a string such as:
"0123456789"
And I need to split each character into an array.
I, for the hell of it, tried:
explode('', '123545789');
But it gave me the obvious: Warning: No delimiter defined in explode) ..
How would I come across this? I can't see any method off hand, especially just a function.
$array = str_split("0123456789bcdfghjkmnpqrstvwxyz");
str_split takes an optional 2nd param, the chunk length (default 1), so you can do things like:
$array = str_split("aabbccdd", 2);
// $array[0] = aa
// $array[1] = bb
// $array[2] = cc etc ...
You can also get at parts of your string by treating it as an array:
$string = "hello";
echo $string[1];
// outputs "e"
You can access characters in a string just like an array:
$s = 'abcd';
echo $s[0];
prints 'a'
Try this:
$str = '123456789';
$char_array = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
str_split can do the trick. Note that strings in PHP can be accessed just like a character array. In most cases, you won't need to split your string into a "new" array.
Here is an example that works with multibyte (UTF-8) strings.
$str = 'äbcd';
// PHP 5.4.8 allows null as the third argument of mb_strpos() function
do {
$arr[] = mb_substr( $str, 0, 1, 'utf-8' );
} while ( $str = mb_substr( $str, 1, mb_strlen( $str ), 'utf-8' ) );
It can be also done with preg_split() (preg_split( '//u', $str, null, PREG_SPLIT_NO_EMPTY )), but unlike the above example, that runs almost as fast regardless of the size of the string, preg_split() is fast with small strings, but a lot slower with large ones.
Try this:
$str = '546788';
$char_array = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
Try this:
$str = "Hello Friend";
$arr1 = str_split($str);
$arr2 = str_split($str, 3);
print_r($arr1);
print_r($arr2);
The above example will output:
Array
(
[0] => H
[1] => e
[2] => l
[3] => l
[4] => o
[5] =>
[6] => F
[7] => r
[8] => i
[9] => e
[10] => n
[11] => d
)
Array
(
[0] => Hel
[1] => lo
[2] => Fri
[3] => end
)
If you want to split the string, it's best to use:
$array = str_split($string);
When you have a delimiter, which separates the string, you can try,
explode('', $string);
Where you can pass the delimiter in the first variable inside the explode such as:
explode(',', $string);
$array = str_split("$string");
will actually work pretty fine, but if you want to preserve the special characters in that string, and you want to do some manipulation with them, then I would use
do {
$array[] = mb_substr($string, 0, 1, 'utf-8');
} while ($string = mb_substr($string, 1, mb_strlen($string), 'utf-8'));
because for some of mine personal uses, it has been shown to be more reliable when there is an issue with special characters.

Categories