I'm having way too much trouble with this simple problem: split a string into an array of 2-character values, i.e.
$string = 'abcdefgh';
// With the correct regex, should return ['ab','cd','ef','gh'];
$array = preg_split("/?????/",$string);
What's the darn regex?
Use str_split() instead.
$chunks = str_split($string, 2);
Hint: If you split ON the characters, you end up with an array of 4 elements that are blank
eg.
/../i
I don't think the preg_split is what you want, perhaps preg_match_all? eg.
$cnt = preg_match_all('/../i', $string, $matches);
Related
I've filtered some keywords from a string, to remove invalid ones but now I have a lot of extra commas. How do I remove them so I go from this:
,,,,,apples,,,,,,oranges,pears,,kiwis,,
To this
apples,oranges,pears,kiwis
This question is unique because it also deals with commas at the start and end.
$string = preg_replace("/,+/", ",", $string);
basically, you use a regex looking for any bunch of commas and replace those with a single comma.
it's really a very basic regular expression. you should learn about those!
https://regex101.com/ will help with that very much.
Oh, forgot: to remove commas in front or after, use
$string = trim($string, ",");
Use PHP's explode() and array_filter() functions.
Steps:
1) Explode the string with comma.
2) You will get an array.
3) Filter it with array_filter(). This will remove blank elements from array.
4) Again, implode() the resultant array with comma.
5) You will get commas removed from the string.
<?php
$str = ',,,,,apples,,,,,,oranges,pears,,kiwis,,';
$arr = explode(',', $str);
$arr = array_filter($arr);
echo implode(',', $arr);// apples,oranges,pears,kiwis
?>
You can also achieve this by using preg_split and array_filter.
$string = ",,,,,apples,,,,,,oranges,pears,,kiwis,,";
$keywords = preg_split("/[\s,]+/", $string);
$filterd = array_filter($keywords);
echo implode(",",$filterd);
Result:
apples,oranges,pears,kiwis
Explanation:
split with comma "," into an array
use array_filter for removing empty indexes.
implode array with "," and print.
From Manual: preg_split — Split string by a regular expression (PHP 4, PHP 5, PHP 7)
How about using preg_replace and trim?
$str=',,,,,apples,,,,,,oranges,pears,,kiwis,,';
echo trim( preg_replace('#,{2,}#',',',$str), ',');
I am using explode to extract only strings from a whole line. However using this:
$array = explode(" ", $line);
It splits the line by only one space, not by words. For example if $line is
$line="word1 word2 word3"
then I also have spaces among the entries in the array (it contains: "word1", "word2" and "word3", but also one or two " ").
Does anyone know how to obtain only the three entries "word1", "word2" and "word3" in the array ?
Use preg_split , to split on one or more whitespace characters:
$array = preg_split('/\s+/', $line);
Unlike explode (which splits on a string), preg_split splits on a regular expression, so it is more flexible. If you don't need to use a regular expression for your delimiter, you should instead use explode.
Use str_word_count() with a format code or 1 or 2, and a char list indicating that digits should be considered part of the word, because this will also handle splitting against punctuation marks
$array = str_word_count($line, 1, '0123456789');
Personally I would use Tom Fenech's answer but for your existing code:
$array = array_filter(explode(" ", $line));
You can remove empty array values with array filter:
$array = array_filter(explode(" ", $line));
I have an alpha numeric string say for example,
abc123bcd , bdfnd567, dfd89ds.
I want to trim all the characters before the first appearance of any integer in the string.
My result should look like,
abc , bdfnd, dfd.
I am thinking of using substr. But not sure how to check for a string before first appearance of an integer.
You can easily remove the characters you don't want with preg_replace [docs] and a regular expression:
$str = preg_replace('#\d.*$#', '', $str);
\d matches a digit and .*$ matches any character until the end of the string.
Learn more about regular expressions: http://www.regular-expressions.info/.
DEMO
A possible non-Regex solution would be:
strcspn — Find length of initial segment not matching mask
substr — Return part of a string
Example:
$string = 'foo1bar';
echo substr($string, 0, strcspn($string, '1234567890')); // gives foo
$string = 'abc123bcd';
preg_replace("/[0-9]/", "", $string);
or
trim($string, '0123456789');
I believe you are looking for this?
$matches = array();
preg_match("/^[a-z]+/", "dfd89ds", $matches);
echo $matches[0]; // returns dfd
You can use a regex for this:
$string = 'abc123bcd';
preg_match('/^[a-zA-Z]*/i', $string, $matches);
var_dump($matches[0]);
will produce:
abc
To remove the +/- sign, you can simply use:
abs($number)
and get the absolute value.
e.g
$abs = abs($signed_integer);
I am trying to filter out all characters before the first / sign. I have strings like
ABC/123/...
and I am trying to filter out ABC, 123 and ... into separate strings. I have alsmost succeeded with the parsing of the first letters before the / sign except that the / sign is part of the match, which I don´t want to.
<?php
$string = "ABC/123/...";
$pattern = '/.*?\//';
preg_match($pattern, $string, $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
?>
The letters before the first/ can differ both in length and characters, so a string could also look like EEEE/1111/aaaa.
If you are trying to split the string using / as the delimiter, you can use explode.
$array = explode("/", $string);
And if you are looking only for the first element, you can use array_shift.
$array = array_shift(explode("/", $string));
I have to make a regex for two choices, for exemple I have a string:
apps; chrome
I have to split the string in 2 pieces without spaces
1-> apps
2-> chrome
but the problem is that string might be "apps;chrome" (w/o space after ;)
I tried with explode
$part = explode(";", $search);
If the string is with space between characters the second piece have a space.
What I want is a regex for following cases to split them in 2 pieces
apps; chrome
apps;chrome
I hope you understand, sorry for my english :)
The trim function will help:
list($k1,$k2) = array_map("trim",explode(";",$search));
One-liner! =3
Try using trim on the various parts.
e.g.
$parts = array_map('trim', explode(';', $search));
Well, if you are sure about the separators, and you have two options, basically.
1) Using explode(';', $string) and array_map
This will explode the string and them apply trim() over the array;
$slices = explode(';', $string);
$slices_filtered = array_map("trim", $slices);
2) Using preg_split("/[,; \t\n]+/",$string);
This will split strings like "we , are; the \n champions" into {we,are,the,champions}
$slices_filtered = preg_split("/[,; \t\n]+/",$string);
** considering the 'options' won't have spaces on it; if they do, you should use some pattern like
/[,;][ ]*/
Just because you'd specified a Regular Expression ... and this should allow you to match any 2 lower-case alpha strings separated by a semi-colon, with any number (or type) of whitespace "noise".
$sFullString = "app; chrome"; //or wherever you're getting your string from
//RegExp pattern to match many strings including "app;chrome"
$sRegExp = '/^\s*([a-z]+);\s*([a-z]+)\s*$/';
//first replacement
$sAppMatch = preg_replace($sRegExp, "$1", $sFullString);
//second replacement
$sChromeMatch = preg_replace($sRegExp, "$2", $sFillString);
Just use a trim() function before treating your $parts
Why regex?
<?php
$parts = explode(";", $search);
foreach ($parts as $k => $v) {
$parts[$k]=trim($v);
}