preg_match with two choices - php

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);
}

Related

Remove excess commas from string PHP

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), ',');

Using preg_replace to modify first space, but not inside a group of words using PHP

I would like to replace commas and potential spaces (i.e. that user can type or not) of an expression using preg_replace.
$expression = 'alfa,beta, gamma gmm, delta dlt, epsilon psln';
but I was unable to format the output as I want:
'alfa|beta|gamma gmm|delta dlt|epsilon psln'
Amongst others I tried this:
preg_replace (/,\s+/, '|', $expression);
and although it was the closest I got, it's not yet right. With code above I receive:
alfa,beta|gamm|gmm|delt|dlt|epsilo|psl|
Then I tried this (with | = OR):
preg_replace (/,\s+|,/, '|', $expression);
and although I solved the problem with the comma, it is still wrong:
alfa|beta|gamm|gmm|delt|dlt|epsilo|psl|
What should I do to only delete space after comma and not inside the word-group?
Many thanks in advance!
Use ,\s* instead of ,\s+ and replace the matched characters with | symbol. If you use ,\s+, it matches the commas and the following one or more spaces but it forgot the commas which are alone. By making the occurrence of spaces to zero or more times, it would also match the commas which are alone.
DEMO
Code:
<?php
$string = 'alfa,beta, gamma gmm, delta dlt, epsilon psln';
$pattern = "~,\s*~";
$replacement = "|";
echo preg_replace($pattern, $replacement, $string);
?>
Output:
alfa|beta|gamma gmm|delta dlt|epsilon psln
How about using regular PHP functions to achieve this?
<?php
$expression = 'alfa,beta, gamma gmm, delta dlt, epsilon psln';
$pieces = explode(',', $expression);
foreach($pieces as $k => $v)
$pieces[$k] = trim($v);
$result = implode('|', $pieces);
echo $result;
?>
Output:
alfa|beta|gamma gmm|delta dlt|epsilon psln
This will distinguish between spaces at start/end of piece and spaces in pieces.

Extract strings only from a line in php

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));

PHP Regex 2 words per group

I've been wondering, is it possible to group every 2 words using regex? For 1 word i use this:
((?:\w'|\w|-)+)
This works great. But i need it for 2 (or even more words later on).
But if I use this one:
((?:\w'|\w|-)+) ((?:\w'|\w|-)+) it will make groups of 2 but not really how i want it. And when it encounters a special char it will start over.
Let me give you an example:
If I use it on this text: This is an . example text using & my / Regex expression
It will make groups of
This is
example text
regex expression
and i want groups like this:
This is
is an
an example
example text
text using
using my
my regex
regex expression
It is okay if it resets after a . So that it won't match hello . guys together for example.
Is this even possible to accomplish? I've just started experimenting with RegEx so i don't quite know the possibilities with this.
If this isn't possible could you point me in a direction that I should take with my problem?
Thanks in advance!
Regex is an overkill for this. Simply collect the words, then create the pairs:
$a = array('one', 'two', 'three', 'four');
$pairs = array();
$prev = null;
foreach($a as $word) {
if ($prev !== null) {
$pairs[] = "$prev $word";
}
$prev = $word;
}
Live demo: http://ideone.com/8dqAkz
try this
$samp = "This is an . example text using & my / Regex expression";
//removes anything other than alphabets
$samp = preg_replace('/[^A-Z ]/i', "", $samp);
//removes extra spaces
$samp = str_replace(" "," ",$samp);
//the following code splits the sentence into words
$jk = explode(" ",$samp);
$i = sizeof($jk);
$j = 0;
//this combines words in desired format
$array="";
for($j=0;$j<$i-1;$j++)
{
$array[] = $jk[$j]." ".$jk[$j+1];
}
print_r($array);
Demo
EDIT
for your question
I've changed the regex like this: "/[^A-Z0-9-' ]/i" so it doesn't
mess up words like 'you're' and '9-year-old' for example. But by doing
this when there is a seperate - or ' in my text, it will treat those
as a seperate words. I know why it does this but is it preventable?
change the regex like this
preg_replace('/[^A-Z0-9 ]+[^A-Z0-9\'-]/i', "", $samp)
Demo
First, strip out non-word characters (replace \W with '') Then perform your match. Many problems can be made simpler by breaking them down. Regexes are no exception.
Alternatively, strip out non-word characters, condense whitespace into single spaces, then use explode on space and array_chunk to group your words into pairs.

php string replace/remove

Say I have strings: "Sports Car (45%)", or "Truck (50%)", how can I convert them to "Sports_Car" and "Truck".
I know about str_replace or whatever but how do I clip the brackets and numbers part off the end? That's the part I'm struggling with.
You can do:
$s = "Sports Car (45%)";
$s = preg_replace(array('/\([^)]*\)/','/^\s*|\s*$/','/ /'),array('','','_'),$s);
See it
There are a few options here, but I would do one of these:
// str_replace() the spaces to _, and rtrim() numbers/percents/brackets/spaces/underscores
$result = str_replace(' ','_',rtrim($str,'01234567890%() _'));
or
// Split by spaces, remove the last element and join by underscores
$split = explode(' ',$str);
array_pop($split);
$result = implode('_',$split);
or you could use one of a thousand regular expression approaches, as suggested by the other answers.
Deciding which approach to use depends on exactly how your strings are formatted, and how sure you are that the format will always remain the same. The regex approach is potentially more complicated but could afford finer-grained control in the long term.
A simple regex should be able to achieve that:
$str = preg_replace('#\([0-9]+%\)#', '', $str);
Of course, you could also choose to use strstr() to look for the (
You can do that using explode:
<?php
$string = "Sports Car (45%)";
$arr = explode(" (",$string);
$answer = $arr[0];
echo $answer;
?>

Categories