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), ',');
Related
i've scraped a html string from a website. In this string it contains multiple strings like color:#0269D2. How can i make str_replace code which replace this string with another color ?
For instance something like this just looping through all color:#0269D in the fulltext string variable?
str_replace("color:#0269D","color:#000000",$fulltext);
you pass array to str_replace function , no need to use loop
$a= array("color:#0269D","color:#000000");
$str= str_replace($a,"", $string);
You have the right syntax. I would add a check:
$newText = str_replace("color:#0269D", "color:#000000", $fulltext, $count);
if($count){
echo "Replaced $count occurrences of 'color'.";
}
This code might be too greedy for what you're looking to do. Careful. Also if the string differs at all, for example color: #0269D, this replacement will not happen.
’str_replace’ already replaces all occurrences of the search string with the replacement string.
If you want to replace all colors but aren't sure which hexcodes you'll find you could use preg_replace to match multiple occurrences of a pattern with a regular expression and replace it.
In your case:
$str = "String with loads of color:#000000";
$pattern = '/color ?: ?#[0-9a-f]{3,6}/i';
$replacement = "color:#FFFFFF";
$result = preg_replace($pattern, $replacement, $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 a string that contains many underscores followed by words ex: "Field_4_txtbox" I need to find the last underscore in the string and remove everything following it(including the "_"), so it would return to me "Field_4" but I need this to work for different length ending strings. So I can't just trim a fixed length.
I know I can do an If statement that checks for certain endings like
if(strstr($key,'chkbox')) {
$string= rtrim($key, '_chkbox');
}
but I would like to do this in one go with a regex pattern, how can I accomplish this?
The matching regex would be:
/_[^_]*$/
Just replace that with '':
preg_replace( '/_[^_]*$/', '', your_string );
There is no need to use an extremly costly regex, a simple strrpos() would do the job:
$string=substr($key,0,strrpos($key,"_"));
strrpos — Find the position of the last occurrence of a substring in a string
You can also just use explode():
$string = 'Field_4_txtbox';
$temp = explode('_', strrev($string), 2);
$string = strrev($temp[1]);
echo $string;
As of PHP 5.4+
$string = 'Field_4_txtbox';
$string = strrev(explode('_', strrev($string), 2)[1]);
echo $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);
}
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);