php preg_match() code for comma separated names - php

I need to validate input patterns using preg_match() so that the patterns is like " anyname1,anyname2,anyname3, ".
Note that there is a comma at the end too. Any letter or number is valid between the commas, numbers do not have to appear at the end. e.g "nam1e,Na2me,NNm22," is valid.
I tried ^([A-Za-z0-9] *, *)*[A-Za-z0-9]$ but did no work. I have gone through other posts too but did not get a perfect answer.
Can someone give me an answer for this?

If you just want the actual values without the comma, then you can simply use this:
\w+(?=[,])
http://regex101.com/r/xT6wE4/1

It sounds like you want to validate that the string contains a series of comma separated alpha-numeric substrings, with an optional trailing comma.
In that situation, this should achieve what you want.
$str = "anyname1,anyname2,anyname3,";
$re = '~^([a-z0-9]+,)+$~i';
if (preg_match($re, $str)) {
// String matches the pattern!
}
else {
// Nope!
}
If the value stored in $str contains a trailing space like in your example, and you don't want to use trim() on the value, the following regex will allow for whitespace at the end of $str:
~^([a-z0-9]+,)+\s*$~i

Why use such a complex solution for a simple problem? You can do the same in two steps:
1: trim spaces, line feeds, line returns and comma's:
$line = trim($line," \r\n,");
2: explode on comma's to see all the names:
$array = explode(',',$line);
You're not telling us what you're going to use it for, so I cannot know which format you really need. But my point is that you don't need complex string functions to do simple tasks.

^([a-zA-Z0-9]+,)+$
You can simply do this.See demo.
http://regex101.com/r/yR3mM3/8

Related

Use regex to quote the name in name-value pair of a list of pairs

I am trying to put quotes around the names of name-value pairs separated by commas. I use preg_replace and regex to achieve that. However, my pattern is not working properly.
$str="f1=1,f2='2',f3='a',f4=4,f5='5'";
$newstr=Preg_replace(/'(?.[^=]+)'/,"'$1'",$str);
I expected $newstr to come out like so:
'f1'=1,'f2'='2','f3'='a','f4'=4,'f5'='5'
But it doesn't and the qoutes don't contain the name.
What should the pattern be and how can I use the comma to get all of them correctly?
There are a few issues with your attempt:
PHP does not have a regex-literal syntax as in JavaScript, so starting the regex value with a forward slash is a syntax error. It should be a string, so start with a quote. Maybe you accidently swapped the slash and quote at the start and the end.
(?. is not valid. Maybe you intended (?:, but then there is no capture group and $1 is not a valid back reference. To have the capture group, you should not have (?., but just (.
[^=]+ could include substrings like 1,f2. There should be logic to not start matching while still inside a value (whether quoted or not).
I would suggest a regex where you match both parts around the = (both key and value), and then in the replacement, just reproduce the second part without change. This will ensure you don't accidently use anything in the value side for wrapping in quotes:
$newstr = preg_replace("/([^,=]+)=('[^']*'|[^,]*)/","'$1'=$2",$str);
Basically, match beginning of line or a comma (with negative capture) and then capture everything until a =
$reg = "/(?<=^|,)([^=]+)/";
$str = "f1=1,f2='2',f3='a',f4=4,f5='5'";
print_r(preg_replace($reg, "'$1'", $str));
// output:
// 'f1'=1,'f2'='2','f3'='a','f4'=4,'f5'='5'
This will also work, a different approach, but assuming there will be no comma in the values or names except the separators..
$newstr = preg_replace("/(.)(?==)|(?<=,|^)(.)/", "$1'$2", $str);
But I believe string and simple array operations will be faster as the regex is really getting complex and there are so many steps to get the characters.. Here is the same output but with array functions only.
$newstr = implode(",", array_map(function($element){ return "'". implode("'=", explode("=", $element)); }, explode(",", $str)));
RegEx is not always fast than string or array operations, but yes it can do complex things with little bit of code.

preg_replace - similar patterns

I have a string that contains something like "LAB_FF, LAB_FF12" and I'm trying to use preg_replace to look for both patterns and replace them with different strings using a pattern match of;
/LAB_[0-9A-F]{2}|LAB_[0-9A-F]{4}/
So input would be
LAB_FF, LAB_FF12
and the output would need to be
DAB_FF, HAD_FF12
Problem is, for the second string, it interprets it as "LAB_FF" instead of "LAB_FF12" and so the output is
DAB_FF, DAB_FF
I've tried splitting the input line out using 2 different preg_match statements, the first looking for the {2} pattern and the second looking for the {4} pattern. This sort of works in that I can get the correct output into 2 separate strings but then can't combine the two strings to give the single amended output.
\b is word boundary. Meaning it will look at where the word ends and not only pattern match.
https://regex101.com/r/upY0gn/1
$pattern = "/\bLAB_[0-9A-F]{2}\b|\bLAB_[0-9A-F]{4}\b/";
Seeing the comment on the other answer about how to replace the string.
This is one way.
The pattern will create empty entries in the output array for each pattern that fails.
In this case one (the first).
Then it's just a matter of substr.
$re = '/(\bLAB_[0-9A-F]{2}\b)|(\bLAB_[0-9A-F]{4}\b)/';
$str = 'LAB_FF12';
preg_match($re, $str, $matches);
var_dump($matches);
$substitutes = ["", "DAB", "HAD"];
For($i=1; $i<count($matches); $i++){
If($matches[$i] != ""){
$result = $substitutes[$i] . substr($matches[$i],3);
Break;
}
}
Echo $result;
https://3v4l.org/gRvHv
You can specify exact amounts in one set of curly braces, e.g. `{2,4}.
Just tested this and seems to work:
/LAB_[0-9A-F]{2,4}/
LAB_FF, LAB_FFF, LAB_FFFF
EDIT: My mistake, that actually matches between 2 and 4. If you change the order of your selections it matches the first it comes to, e.g.
/LAB_([0-9A-F]{4}|[0-9A-F]{2})/
LAB_FF, LAB_FFFF
EDIT2: The following will match LAB_even_amount_of_characters:
/LAB_([0-9A-F]{2})+/
LAB_FF, LAB_FFFF, LAB_FFFFFF...

Regex for PHP seems simple but is killing me

I'm trying to make a replace in a string with a regex, and I really hope the community can help me.
I have this string :
031,02a,009,a,aaa,AZ,AZE,02B,975,135
And my goal is to remove the opposite of this regex
[09][0-9]{2}|[09][0-9][A-Za-z]
i.e.
a,aaa,AZ,AZE,135
(to see it in action : http://regexr.com?3795f )
My final goal is to preg_replace the first string to only get
031,02a,009,02B,975
(to see it in action : http://regexr.com?3795f )
I'm open to all solution, but I admit that I really like to make this work with a preg_replace if it's possible (It became something like a personnal challenge)
Thanks for all help !
As #Taemyr pointed out in comments, my previous solution (using a lookbehind assertion) was incorrect, as it would consume 3 characters at a time even while substrings weren't always 3 characters.
Let's use a lookahead assertion instead to get around this:
'/(^|,)(?![09][0-9]{2}|[09][0-9][A-Za-z])[^,]*/'
The above matches the beginning of the string or a comma, then checks that what follows does not match one of the two forms you've specified to keep, and given that this condition passes, matches as many non-comma characters as possible.
However, this is identical to #anubhava's solution, meaning it has the same weakness, in that it can leave a leading comma in some cases. See this Ideone demo.
ltriming the comma is the clean way to go there, but then again, if you were looking for the "clean way to go," you wouldn't be trying to use a single preg_replace to begin with, right? Your question is whether it's possible to do this without using any other PHP functions.
The anwer is yes. We can take
'/(^|,)foo/'
and distribute the alternation,
'/^foo|,foo/'
so that we can tack on the extra comma we wish to capture only in the first case, i.e.
'/^foo,|,foo/'
That's going to be one hairy expression when we substitute foo with our actual regex, isn't it. Thankfully, PHP supports recursive patterns, so that we can rewrite the above as
'/^(foo),|,(?1)/'
And there you have it. Substituting foo for what it is, we get
'/^((?![09][0-9]{2}|[09][0-9][A-Za-z])[^,]*),|,(?1)/'
which indeed works, as shown in this second Ideone demo.
Let's take some time here to simplify your expression, though. [0-9] is equivalent to \d, and you can use case-insensitive matching by adding /i, like so:
'/^((?![09]\d{2}|[09]\d[a-z])[^,]*),|,(?1)/i'
You might even compact the inner alternation:
'/^((?![09]\d(\d|[a-z]))[^,]*),|,(?1)/i'
Try it in more steps:
$newList = array();
foreach (explode(',', $list) as $element) {
if (!preg_match('/[09][0-9]{2}|[09][0-9][A-Za-z]/', $element) {
$newList[] = $element;
}
}
$list = implode(',', $newList);
You still have your regex, see! Personnal challenge completed.
Try matching what you want to keep and then joining it with commas:
preg_match_all('/[09][0-9]{2}|[09][0-9][A-Za-z]/', $input, $matches);
$result = implode(',', $matches);
The problem you'll be facing with preg_replace is the extra-commas you'll have to strip, cause you don't just want to remove aaa, you actually want to remove aaa, or ,aaa. Now what when you have things to remove both at the beginning and at the end of the string? You can't just say "I'll just strip the comma before", because that might lead to an extra comma at the beginning of the string, and vice-versa. So basically, unless you want to mess with lookaheads and/or lookbehinds, you'd better do this in two steps.
This should work for you:
$s = '031,02a,009,a,aaa,AZ,AZE,02B,975,135';
echo ltrim(preg_replace('/(^|,)(?![09][0-9]{2}|[09][0-9][A-Za-z])[^,]+/', '', $s), ',');
OUTPUT:
031,02a,009,02B,975
Try this:
preg_replace('/(^|,)[1-8a-z][^,]*/i', '', $string);
this will remove all substrings starting with the start of the string or a comma, followed by a non allowed first character, up to but excluding the following comma.
As per #GeoffreyBachelet suggestion, to remove residual commas, you should do:
trim(preg_replace('/(^|,)[1-8a-z][^,]*/i', '', $string), ',');

How to get text without some word (an ampersand issue)

I have a string like this: Hello #"user name". Where are you from, #"user name"?
I need to get the string between the " statements (user name), but I don't know how to do it.
I tried something like this /#("(.*)"|(.[^ ]*))\s*/ but it works wrong
First off, one possible regular expression that grabs the data you need is #"(.+?)", which matches any data within quotes preceded by #, and captures the data inside. Now that you've added the regex you've tried, I'm betting that the issue is that your expression is greedy: the regex engine tries to grab the longest match possible, so returns all of #"user name". Where are you from, #"user name". Adding the ? makes the expression lazy, so it will grab the shorter match.
Since you're interested in the content inside, I'm guessing that your final goal is to replace those strings with various types of user data dynamically, so one approach would be preg_replace_callback:
function user_data($matches) {
$key = $matches[1];
// return the user data for a $key like "user name"
}
$output = preg_replace_callback('/#"(.+?)"/', 'user_data', $input);
try looking at this: http://www.php.net/manual/en/function.strstr.php you might need to explode the white space after and get the first item from the array as well.
If there is only one #"..." per string, something like this should work
$matches = array();
preg_match("/#\"(.+?)\"/i", $inputstring, $matches);
echo($matches[1]);
Try this, if its not working, just escape " in pattern
/\#\&quote\;([\w\s]{0,})\&quote\;/

regular expr question

i'v got such string <>1 <>2 <>3
i want remove all '<>' and symbols after '<>' i want replace with such expression like www.test.com/1.jpg, www.test.com/2.jpg, www.test.com/3.jpg
is it possible to do with regex? i only know to find '/<>.?/'
preg_replace('/<>(\d+)/g', 'www.test.com/bla/$1.jpg', $input);
(assuming your replaced elements are just numbers. If they are more general, you'll need to replace '\d+' by something else).
str_replace('<>', 'www.test.com/', $input);
// pseudo code
pre_replace_all('~<>([0-9]+)~', 'www.test.com/$1.jpg', $input);
$string = '<>1 <>2 <>3';
$temp = explode(' ',preg_replace('/<>(\d)/','www.test.com/\1.jpg',$string));
$newString = implode(', ',$temp);
echo $newString;
Based on your example, I don’t think you need regex at all.
$str = '<>1 <>2 <>3';
print_r(str_replace('<>', 'www.test.com/', $str));
Regex's allow you to manipulate a string in any fashion you desire, to modify the string in the fashion you desire you would use the following regex:
<>(\d)
and you would use regex back referencing to keep the values you have captured in your grouping brackets, in this case a single digit. The back reference is typically signified by the $ symbol and then the number of the group you are referencing. As follows:
www.test.com/$1
this would be used in a regex replace scenario which would be implemented in different ways depending on the language you are implementing your regex replace method in.

Categories