using regex to find invalid postcode - php

I'm new to php and I'm trying to write a function to find an invalid postcode. This is an option, however I've been told this isnt the ideal format:
function postcode_valid($postcode) {
return preg_match('/\w{2,3} \d\w{2}/', $postcode);
}
//more accurate
//[A-Z]{1,2}[0-9]{1,2}[A-Z]? [0-9][A-Z]{2}
I understand the first function, but I don't know how to write the 'ideal' solution as a function, please can you advise?

If the regular expression you provided in the comment field is the correct one and you don't know how to use it in PHP, here is the solution:
function postcode_valid($postcode) {
return preg_match('/^[A-Z]{1,2}[0-9]{1,2}[A-Z]? [0-9][A-Z]{2}$/', $postcode);
}
You need to add two slashes (one in front, one at the end) of the regular expression and pack it in a string in PHP. I would also highly recommend you to use ^ and $ at the beginning resp. at the end of the regular expression to indicate the beginning and the end of the string (otherwise, it is valid, if only a part of the string contains the correct pattern i.e. a longer string with a valid part would be accepted.) Here is a live example.
If you are looking for the validation of a UK post code, you should be using the following regex instead (source):
(GIR 0AA)|((([A-Z-[QVX]][0-9][0-9]?)|(([A-Z-[QVX]][A-Z-[IJZ]][0-9][0-9]?)|(([A-Z-[QVX]][0-9][A-HJKPSTUW])|([A-Z-[QVX]][A-Z-[IJZ]][0-9][ABEHMNPRVWXY])))) [0-9][A-Z-[CIKMOV]]{2})
If you are looking for something else, please provide a comment below.

Related

How to parse a string using regex or another technique?

I need to parse the id from the following string:
https://itunes.apple.com/us/album/24k-magic/id1161503945?i=1161504024&uo=2
I need to only return the following:
id1161503945
The string always begins with https://itunes.apple.com/ and ends with ?i=#####&uo=2
I tried string and replace with wildcards but that did not work.
Well, you can use this below regex. It is working. I have use preg_replace function.
$data = 'https://itunes.apple.com/us/album/24k-magic/id1161503945?i=1161504024&uo=2';
echo preg_replace("/(.*)\/(\w+)\?(.*)/","$2",$data);
Output is
id1161503945
Or You can use
preg_match("/(\/)(\w+)(\?)/",$data,$m);
echo $m[2];
Same output.
Hope it help you
If it's really always the last element (before query params) in the url, then you can use this simple regex:
'/id[^?]+/'
CAUTION: as pointed by #xhienne, this works only if you're sure that another id string doesn't appear anywhere before the searched part.
If it may happen, rather use:
'/id[\d]+/'
This way, it's safe with respect to a previous id string, but the searched id must be followed by digits only.

regex with preg_match anything and all line breaks

i am not too good with regex and can't seem to find the answer
I am writing a class file to check data type and "partially/best possible sanitise" any submitted data as well as performing some other functions too. This is working on all data types (i.e emails, url's phone numbers, int/signed/un-signed, words, passwords, various date formats, basic HTML, etc)
i am having problems with trying to match "anything"* (this is the one data type i dont really need to check, but for consistency, i need it to run through the preg_match, but always want it to return true).
when i say "anything" i want it to match any text, number, symbols AND Line Breaks. It is the line break i am having problems with
i am using :
define('REG_TEXT', '/^(.*)$/');
preg_match(REG_TEXT, $data)
this works fine on the first paragraph, but wont match past any line beaks so returns false
an example of what i want this to match (return true) would be:
this is a test match on anything 345 +_)(*&^%$£"!<br><html> <?php echo this i PHP; ?>
and match this too on a new line
and match all this line too
and anything else at all
i am not worried about any code in-putted into the data at this point as other areas of my class are dealing with this (before this stage!).
basically i am after a regex that will match/return true on absolutely anything.
(i dont want to change to preg_match_all as this will break other aspects of the class or require me to add additional code that will be a partial repeat of code that i dont think is needed)
any advice would be greatly welcomed!
thanks
Jon
Use:
'/^(.*)$/ms'
You need the m and s modifiers here. http://php.net/manual/en/reference.pcre.pattern.modifiers.php

Using preg_match_all to filter out strings containing this but not this

im having an issue with preg_match_all. I have this string:
$product_req = "ACTIVE-6,CATEGORY-ACTIVE-8,CATEGORY-ACTIVE-4,ACTIVE-9";
I need to get the numbers preceded by "ACTIVE-" but not by "CATEGORY-ACTIVE-", so in this case the result should be 6,9. I used the statement below:
preg_match_all("/ACTIVE-(\d+)/", $product_req, $this_act);
However this will return all the numbers because all of them are in fact preceded by "ACTIVE-" but thats not what i meant because i need to leave out those preceded by "CATEGORY-ACTIVE-". How can i configure preg_match_all to do it? Or maybe there is some other function that can do the job?
EDIT:
I tried this:
preg_match_all("/CATEGORY-ACTIVE-(\d+)/", $product_req, $this_cat_act);
preg_match_all("/ACTIVE-(\d+)/", $product_req, $this_act);
$act_cat = str_replace($this_cat_act[1],"",$this_act[1]);
it kinda works, but i guess there is a better and cleaner way to do it. Besides the output is kinda weird too.
Thank you.

PHP Regex URL parsing issues preg_replace

I have a custom markup parsing function that has been working very well for many years. I recently discovered a bug that I hadn't noticed before and I haven't been able to fix it. If anyone can help me with this that'd be awesome. So I have a custom built forum and text based MMORPG and every input is sanitized and parsed for bbcode like markup. It'll also parse out URL's and make them into legit links that go to an exit page with a disclaimer that you're leaving the site... So the issue that I'm having is that when I user posts multiple URL's in a text box (let's say \n delimited) it'll only convert every other URL into a link. Here's the parser for URL's:
$markup = preg_replace("/(^|[^=\"\/])\b((\w+:\/\/|www\.)[^\s<]+)" . "((\W+|\b)([\s<]|$))/ei", '"$1".shortURL("$2")."$4"', $markup);
As you can see it calls a PHP function, but that's not the issue here. Then entire text block is passed into this preg_replace at the same time rather than line by line or any other means.
If there's a simpler way of writing this preg_replace, please let me know
If you can figure out why this is only parsing every other URL, that's my ultimate goal here
Example INPUT:
http://skylnk.co/tRRTnb
http://skylnk.co/hkIJBT
http://skylnk.co/vUMGQo
http://skylnk.co/USOLfW
http://skylnk.co/BPlaJl
http://skylnk.co/tqcPbL
http://skylnk.co/jJTjRs
http://skylnk.co/itmhJs
http://skylnk.co/llUBAR
http://skylnk.co/XDJZxD
Example OUTPUT:
http://skylnk.co/tRRTnb
<br>http://skylnk.co/hkIJBT
<br>http://skylnk.co/vUMGQo
<br>http://skylnk.co/USOLfW
<br>http://skylnk.co/BPlaJl
<br>http://skylnk.co/tqcPbL
<br>http://skylnk.co/jJTjRs
<br>http://skylnk.co/itmhJs
<br>http://skylnk.co/llUBAR
<br>http://skylnk.co/XDJZxD
<br>
e flag in preg_replace is deprecated. You can use preg_replace_callback to access the same functionality.
i flag is useless here, since \w already matches both upper case and lower case, and there is no backreference in your pattern.
I set m flag, which makes the ^ and $ matches the beginning and the end of a line, rather than the beginning and the end of the entire string. This should fix your weird problem of matching every other line.
I also make some of the groups non-capturing (?:pattern) - since the bigger capturing groups have captured the text already.
The code below is not tested. I only tested the regex on regex tester.
preg_replace_callback(
"/(^|[^=\"\/])\b((?:\w+:\/\/|www\.)[^\s<]+)((?:\W+|\b)(?:[\s<]|$))/m",
function ($m) {
return "$m[1]".shortURL($m[2])."$m[3]";
},
$markup
);

regular expression and forward slash

i'm searching for keywords in a string via a regular expression. It works fine for all keywords, exept one which contains a forward slash in it: "time/emit" .
Even using preg_quote($find,'/'), which escapes it, i still get the message:
Unknown modifier 't' in /frontend.functions.php on line 71
If i print the find pattern, it shows /time\\/emit/ . Without preg_quote, it shows /time/emit/ and both return the same error message.
Any bit of knowledge would be useful.
Try to begin and end your regular expression with different sign than /
I personally use `
I've seen people using #
I think most chars are good. You can read more about it here: http://pl.php.net/manual/en/regexp.reference.delimiters.php
Like this:
preg_match('#time/emit#', $subject); // instead of /time/emit/
To put it another way: Your $find variable should contain rather #time/emit# than /time/emit/
looks like you have something already escaping it..
preg_quote('time/emit') // returns time\/emit
preg_quote('time\/emit') // returns time\\/emit
as a hack you could simply do:
preg_quote(stripslashes($find)) // will return time\/emit
bit of code?
the the 'regex' for that particular term should look something like '/time/emit/'. With a set of keywords there may be a more efficient method so seeing what you are doing would be good.
this should work:
$a="Hello////////";
$b=str_replace($a,"//","/");
echo $b;

Categories