FAQ Database Discussion Community


php Regular expression fails

php,regex,preg-match
I'm trying to match string but it is going into last else loop. Can you please provide any help? $cstg = "<result>True<\/result>"; if( preg_match("/<result>True<\/result>/", $cstg)){ echo "result success"; } else if (preg_match("/\<result\>False\<\/result\>/", $cstg)){ echo "result fail"; } else{ echo "Something went wrong."; } ...

How to str_replace Google News RSS for Facebook Share?

regex,rss,preg-match,simplexml,str-replace
Hi I'm using simpleXML to display a news.google.com feed. The displayed entries link to the original article in this way: http://news.google.com/news/url?sa=t&fd=R&ct2=us&usg=AFQjCNEcqhcp4AfUzgxc2l1gumydaxQ-KQ&clid=c3a7d30bb8a4878e06b80cf16b898331&cid=52778832126843&ei=keFLVfiHGvDVmQL5_4GgBg&url=http://WEBSITEWITHNEWS.COM/ARTICLEURLHERE I need the entries to link to this instead: http://WEBSITEWITHNEWS.COM/ARTICLEURLHERE The reason is that Facebook Sharer cannot interpret the following link:...

How can add Preg Match to Match String with dot, Apostrophes

php,regex,preg-match
How can I make Preg Match to Search Strings With ., '," and #? I tried used the following code but it doesnt work if the string contains ., `' . (preg_match("/\b".preg_quote($txtsize,'/')."\b/i", $row['ItemDescription']) Using the above code i couldnt get this on Search 31X15.50-15 12 PLY TRAXION HF2 or 31X15.50...

php preg_match with multiple patterns

php,regex,preg-match
I have two patterns and i want to search them in a string. they are like this: $pattern = '/,3$/' $pattern = '/^1,/'; actually I want to find strings that start with 1, OR end with ,3 My strings are in this format: a => 1,2 b => 31,2 c...

How to make pattern string in preg_match_all

php,regex,preg-match,preg-match-all
How to make one pattern string for preg_match_all() function If I have multiple strings to match like "G,C,D" & "A,B,C" & "E,C,D" Currently my string is $str = "/(?<=\b)([CDEFGAB](?:b|bb|m)*(?:#|##|sus|maj|min|aug)*[\d\/]*(?:[CDEFGAB](?:b|bb‌​|m)*(?:#|##|sus|maj|min|aug)*[\d\/]*)*)(?=\s|$|(<.*>))(?! \w)/" preg_match_all($str,$lyrics , $output_array); I want to add these combinations ("G,C,D" & "A,B,C" & "E,C,D") in $str string....

PHP preg_match returns different value on 2 different servers

php,preg-match
I'm using preg_match() to check if a user inputted string matches a required format. Previously, the local version of the website returned the same value as the production version, however, now the local version is returning False when it should be True. Here's a sample of the code I'm using...

How to find the position of the first occurrence of a pattern using PHP

php,regex,preg-match
I am trying to figure out a way to parse an email. I am stuck trying to figure out how to search for the first occurrence of a text that is in this format > On Mar 12, 2015, at 7:47 AM, Mike G <[email protected]> wrote: the text will start...

PHP - Put special characters from a string into another string

php,preg-match,special-characters
I have a function that I want to tell me what special characters are in a string. I don't want to strip them I want to put into another variable. if (preg_match('/[\'^£$%&*()}{@#~?><>,|=_+¬-]/', $string)) { $special_characters = special characters from $string } Is there a way to do this? Thanks...

replace double qoute with inch PHP [duplicate]

php,regex,preg-replace,preg-match,preg-split
This question already has an answer here: Replace characters in a string? 3 answers I have an variable $query which holds for example 5.6" display or 5.6 " display is there anyway to change it to 5.6 inch display for both of the previous given examples? I tried using...

Preg match for all phone numbers starting with 07045

php,forms,preg-match
I'm trying to add some code that prevents a form entry if the phone number starts with 07405. I've tried the following with no such luck, any ideas? HTML field: <input type="tel" name="required[phone]" placeholder="Telephone Number" data-required="strict"> PHP: case 'phone'; $phone = (sanitize_text_field($fields['phone'])); if (preg_match('07045', $phone)) { $fields['valid_phone'] = $phone; unset($fields['phone']);...

PHP preg_match - regular expression

php,regex,preg-match
I have this text: SU4R C45G G3HD 61U14XE7AR23 914K16W471LV V6SQ5V16LG91 24YL4HW956C3 UZ26J12K615V T741MH4N739W 31ST445G726H 621EH6VW7Q6M 55N629WJ945P 56TX2W6LC949 44DS765CF739 XC262HV1JZ6V 26YD4N1Y71F7 S4M3F1XeDC0D I want to use preg_match to find specific type of code in that text, so I should contains: 4 or 12 characters it should returs all elements non case...

Regex Not Checking ONLY for certain chracters

regex,preg-match
I want my regular expression to check for only uppercase,lowercase characters as well as the characters @, $, ^. This is my reg ex: $string_regex2 = '/^[a-zA-Z0-9\$\^\@]$/'; When I put it in my preg_match function, it seems to still match illegal characters such as '!' or '*'. How change my...

preg_match() with backslashes doesn't work as expected / throws error

php,regex,string,preg-match
I need to preg_match() a pattern in PHP and no matter what I do I get errors. I've looked all over the net and can't find anything that tells me what I'm actually doing wrong. Here's my preg_match pattern: preg_match('/\MyApp\Library\Task\/', '\MyApp\Library\Task\Db\Generate'); It always returns an array, what do I do...

preg_match - What is the pattern of that?

php,regex,preg-match
I have a php class for URL rewriting. I want to route this urls: - services-paris/ - services-paris/8/ - services/ The formula is: services[ "-" + (city) ]? / [ (0-9) + "/" ]? First thing is [ "-" + (city) ]?, means: is optional + must start with "-",...

Shorter way to write strpos with multiple needles in the haystack in PHP

php,preg-match,strpos
I'm checking to see if any of the needles /cgi-bin /css etc are in the haystack $dir. In order to check on multiple needles, I have to write the || after each strpos(). I've seen some other threads on here, but none that really showed the most simplest code. I'm...

Increment for combination of A-Z and 0-9 with unknown format

php,regex,preg-match
i got a table to save the invoice start number, which can let user define in any format, example: ABC123 AZ2D20D7S99 but will force the user end with number i got a table to save all the created invoice with auto_increment so now, i need to display the invoice number...

regex preg_match - undefined offset with filled array

php,arrays,regex,preg-replace,preg-match
I'm trying to parse a BBCode quote with regex. My quote has some variables, which I want to store in PHP variables, so I can use them later on in the code. My BBCode quote looks like this: [quote=user;post_id] TEXT [/quote] My PHP code: function parseQuote($text) { $pattern = '/\[quote=(.*?);(.*?)\](.*?)\[\/quote\]/';...

class.upload error preg_match()

php,regex,preg-match
I use class.upload Version 0.32 and it works correctly on my localhost server, but it does not work on my web server. The web server log file shows this error: PHP Warning: preg_match(): Compilation failed: invalid range in character class at offset 7 in. PHP version on web server: 5.4.39...

Filter a version number out of a string

php,preg-match
I want to filter a number out of a string with php preg_match that could look like this (they are versions of a software): 1.6.2 1.6.2#2 1.7 (1.6.2#2 is 2. beta of 1.6.2) So when there is a string like: Lorem ipsum dolor sit amet, consetetur sadipscing elitr, 1.6.2# sed...

PCRE and PHP - Escaping meta-character

php,preg-match,pcre
I continue to learn about PHP and PCRE. My question today is the following: <?php $search = "Money $ money $ money..."; /*I get "invalid"*/ if(preg_match("&money \$&", $search)){ echo 'Valid <br/>'; }else{ echo 'Invalid <br/>'; } /*I get "valid"*/ if(preg_match('&money \$&', $search)){ echo 'Valid <br/>'; }else{ echo 'Invalid <br/>'; }...

preg_match lookbehind after second slash

php,regex,preg-match
This is my string: stringa/stringb/123456789,abc,cde and after preg_match: preg_match('/(?<=\/).*?(?=,)/',$array,$matches); output is: stringb/123456789 How can I change my preg_match to extract the string after second slash (or after last slash)? Desired output: 123456789 ...

preg_match returns only one (last) result

php,regex,preg-match
I'm trying to parse this string with preg_match function to get name of array and all indexes: {#array[index1][index2][index3] ... } I tried this regex, but in $matches is only the last index ([index3]): $string = "{#array[index1][index2][index3]}"; preg_match('|^\{\#[a-z0-9_\-]+(\[[a-z0-9_-]+\])*\}|i',$string,$matches); results: Array ( [0] => {#array[index1][index2][index3]} [1] => [index3] ) Can somone help...

php preg_match only numbers, letters and dot

php,regex,preg-match
I have been searching for 2 hours now and I still don't get it. I need to evaluate the input of the account name. That can ONLY contain numbers (0-9), letters (a-z and A-Z) and the dot (.). Everything else is forbidden. So, no underscore (_), plus (+) and so...

Regex: Preg_match - Specific search works in English but not in Hebrew

php,regex,preg-match
Trying to match all quotation marks (") that are between: Look-behind - 1 character of anything but [אבג] and 1 character of only [אבג] Look-ahead - Any character [א-ת]. As can be tested - https://www.functions-online.com/preg_match.html - The following works in English: /(?<=[^xyz]{1}[xyz]{1})"(?=[a-z])/i But not in Hebrew: /(?<=[^אבג]{1}[אבג]{1})"(?=[א-ת])/ Any help will...

preg_match_all returning arrays

php,preg-match,preg-match-all
I recently made a small script to catch any URL's that pass through a textarea based on a form submit. The regular expression im using is: '/([\w]+).(local|test|stage|live).site.example.com/' and if submit: <p>body</p> <p>uk2.local.site.example.net training.test.site.example.net</p> <p>www.google.com</p> <p>sd2.test.site.example.net</p> i am returned with an array that contains: 0 => array(3 0 => uk2.local.site.example.net 1...

Validate a PHP variable

php,regex,preg-match
I am trying validate an array of strings to see if they are valid variable names, and if not throw an error. But using my test array (seen below), all keys come back as valid names, and I know that they shouldn't because the first one starts with a 3...

Return from cURL tested with preg_match fails

php,preg-match
From cURL I´m getting back an response array where I´d like to test the body against a regex pattern. Here is a sample array: Array ( [body] => 9068205463|admin [headers] => Array ( [0] => HTTP/1.1 200 OK [1] => Date: Mon, 04 May 2015 16:45:56 GMT [2] => Server:...

Issue with PHP Preg_Match

php,regex,codeigniter,preg-match
I'm working on a CodeIgniter project, and I'm making a custom validation, and I'm no regex expert. So far, I have made a simple test, but I cannot seem to get this right. This validation can only contain A-Z a-z 0-9 and special characters such as: @ ! # /...

How can I match this string '-,-,-,9,-'?

regex,preg-match,regex-negation
I was told to validate the string like this -,-,-,9,- It was separated by , and contains 1 number(0-9), others are all - some examples: 9,-,-,-,- -,-,-,-,9 -,-,2,-,- How can I match this? And what concepts should I learn in regex? Update I miss the times, sorry, this string can...

Check to see if EXACT value is in a string - PHP

php,preg-match,strpos
I have read numerous posts about how to see if a value is in a string. Apparently my request is different since the multiple bits of code haven't worked 100%. I am searching a string and need to make sure the EXACT value is in there - with a perfect...

PHP - Why is my preg_match not working?

php,regex,preg-match
I'm trying to make sure that when the user registers they use a specific series of characters. In my case i want them to enter something like "d1111111" so I want it to be 8 characters in total and to start with the letter d lowercase or uppercase, to allow...

How to make OR operator in regular expression? [duplicate]

php,regex,preg-match
This question already has an answer here: Combining 2 regex expressions 2 answers What i want is something like this: ( [integer OR (ANY but not integer or white-space)] [(ONE white-space OR NONE)] [integer OR (ANY but not integer or white-space)] ) Example of strings that will match: 99...

find a regexpression that matches word boundaries that include accented letters

php,regex,preg-match
I need a regular expression to use in preg_match that will catch words like cialis when as a word with spaces and also as a word with a tag up close ie <b>cialis</b>, so I used this $word = "cialis"; if (preg_match_all("/\b$word\b/i", $content, $matches)) { $caught[] = $matches[0]; } Which...

Extract ID using preg_match not working

php,preg-match
I am trying to use preg_math to extract an ID number from some content like this... $content = "[gravityform id="837" name="Test Form" title="false" description="false"]"; preg_match('/[gravityform\s*id="\s*([0-9]+)/i', $content, $id); echo $id[1]; This isn't working for me though and is returning an error.. preg_match(): Compilation failed: unmatched parentheses Where am I going wrong...

preg_match find regex with or without first capital letter

php,regex,string,preg-match
In my project, I need to find a special regex that works if the first letter is uppercase or lowercase. Here are sample strings: user = username User = username Now, I've tried this regex: '/[^\n]user[^\n]*/' But if first letter is capital, this expression doesn't find anything, so my question...

PHP find 28-character hex regex in string

php,regex,hex,preg-match
In a very long line, i need to find a regex that matches something like this: 01 02 03 04 05 06 07 08 09 10 11 12 13 14 now, that string is always made of hexadecimal characters, so it can be something like this also: ab ba 1a...

preg match on specific amount of decimal characters

php,preg-match
How to match for a specific amount of decimal characters? preg_match('/([0-9]{15,16})[^0-9]/', $input, $matches)) examples no. 05485845150270008225169 => NO MATCH! no. 50270008225169 => NO MATCH! FI 150270008225169 => MATCH! FI 5150270008225169 => MATCH! ...

how to find googleplay id from this text?

php,preg-match
how to find googleplay id from this text with php? it is after Google ID: Short Name: Coin Dozer – World Tour Google ID: com.gamecircus.CoinDozerWorld Version: 3.6 File size: 19.31 MB Category: Games, Casino this is example code but not completed $file = "Short Name: Coin Dozer – World Tour...

PHP preg_match not showing results

php,curl,preg-match
I am trying to scrape this page to get the shipping cost for Standard delivery only. It is not showing results. I have tried different techniques for delimiting special characters. Perhaps there would be a better approach to single out the Standard Cost Price. Any suggestions would be helpful.thanks! <?php...

how to grab only the lines that have Allow from xxx.xxx.xxx.xxx in the .htaccess file

php,regex,preg-match
I am trying to grab all the Allowed addresses in my .htaccess files. currently my .htaccess file looks like this Options +FollowSymlinks RewriteEngine On RewriteRule ^$ /admin [L] Deny from all Allow from 192.168.0.100 Allow from 127.0.0.1 I have this code $myfile = fopen("../.htaccess", "r") or die("Unable to open file!");...

How do I include variable between {} brackets in a php preg_match?

php,variables,preg-match
So I currently have this php code preg_match('/^([^.!?]*[\.!?]+){0,**3**}/', $text, $abstract); Instead of the number 3 I would like it to be a variable example > preg_match('/^([^.!?]*[\.!?]+){0,**$variable**}/', $text, $abstract); Please help thanks a lot :)...

How to dynamically replace text between symbols and replace with a constant in PHP?

php,regex,preg-replace,preg-match
I have a problem where I need to search a HTML page/snippet and replace any value that is between four percentile symbols and convert to a constant variable, e.g. %%THIS_CONSTANT%% becomes THIS_CONSTANT. Right now I am searching through the page, line by line, and I am able to find matches...

preg_match - Regular Expression To Create Array

php,arrays,regex,preg-match
My data - {'/Users/aaron/Applications/developer-vagrant/web/g.php': {'total': 22}} {'/Users/aaron/.vim/autoload/timetap.vim': {'total': 0}} {'/Users/aaron/.vimrc': {'total': 5}} {'/Users/aaron/Documents/Programming/PHP/TimeTapCLI/composer.json': {'total': 144}} {'/Users/aaron/Documents/Programming/PHP/TimeTapCLI/timetap.php': {'total': 351}} {'/Users/aaron/Box/linux/.vim/autoload/timetap.vim': {'total': 37}} {'/Users/aaron/Box/cats.tex': {'total': 184}} I am attempting to create a regular expression so I can convert the above into an...

How to get all the characters between [] using Pregmatch php

php,preg-match
I have a string $str = "[xyz.hlp] into asasa jkljk [xyp.htq] zff [xrt.thg]"; I want to get the character from the string and make an array of all those characters . for example for the above string provided I shuould get and array like this $array("xyz.hlp","xyp.htq","xrt.thg"); I tried using preg_match();...

Remove random spaces in from a string

php,regex,preg-match,data-cleansing
After using pdftotext on a my file there is a field that has spaces between character; the field that has the value for a persons name. Most records are fine, and it appears that usually the last name has this issue; although names are not formatted the same way. When...

Regex filter string number and number not working

c#,.net,regex,preg-match
I am trying to extract a string in this format "[\r\n \"MG480612230220150018\"\r\n]" using regex, i am trying to match number and alphabet with a min length of 5 character but it is not working, therefore i can guarantee i will extract this data (MG480612230220150018) Regex regex = new Regex(@"^[0-9a-zA-Z]{5,}$"); Match...

find “/p” with preg_match in first place of string

php,preg-match
Small problem: $content='/p test some text'; when "/p" is in front of the line the string should be exploded to an array if(preg_match('^(/p)',$content)==true) { $private=explode(" ",$content,3); } i think their is an error, but i've no idea for the correct search parameter...

PHP preg_match specific field value

php,regex,preg-match
I want to get the id or the name of a field that keeps changing its value. Example: I have these fields in my form: <input type="text" id="94245" name="94245" value=""> <input type="text" id="name" name="name" value=""> <input type="text" id="status" name="status" value=""> And I want to get the ID or the name...

Php Preg_Match to get Quoted string in array

php,arrays,string,preg-match
need to get the quoted string and unquoted string in a array Sample Data $string='tennissrchkey1 tennissrchkey2 "tennis srch key 3" "tennis srch key 4" "tennis srch key 5"'; Desired Output Array ( [0] => tennissrchkey1 [1] => tennissrchkey2 [2] => tennis srch key 3 [3] => tennis srch key 4...

PHP - preg_match confusion - not checking for correct character set - needs spaces

php,preg-match
I'm currently building an application that will have addresses inside it and I'm using preg_match to do some character detection and throw an error the user's way if they use invalid characters to make sure it's secure. My problem is using preg_match it seems to be behaving strangely and I...

Reguralexpresion which accepts valid float numbers [PHP]

php,regex,preg-match,conditional
I am trying to verify a valid float number. Basically i want to accept numbers with up to four numbers after the coma: 0,2342 123412,2300 1234.0000 1244 1234,12 1234.12 0.23 I also want to reject the numbers with 0 on the front, but pass the 0 if its on its...

Php preg_match pattern

php,preg-match
I have a form field that I want to check if the user submitted a correct pattern. I tried it this way. // $car_plate should in XXX-1111, or XXX-111(three letters in uppercase followed by a dash and four or three numbers) <?php $car_plate = $values['car_plate']; if (!preg_match('[A-Z]{3}-[0-9]{3|4}$', $car_plate)) { $this->errors...

preg_match - what's wrong with this code?

php,preg-match
$message contains two different Youtube videos. The code below works but the problem is that the end result produces two iframes with the same video ID (the first video). How can I solve this problem? $message = 'This is a text with 2 Youtube videos: https://www.youtube.com/watch?v=rxwMjB-Skao csassasas http://www.youtube.com/watch?v=VWEwWECAokU Enf of...

Unable to match the required phone number format

php,preg-match
I am trying to match a phone number format using preg_match in PHP but I am unable to achieve success. Phone number format that I am trying to match is: +92XXXXXXXXXX First three characters should be +92 and the rest of the remaining should have a count of 10 and...

Regexp - How to check whether a string starts OR ends with given character?

php,regex,string,preg-match
String that start AND ends with that character should not be a match. Is it just easiest to do something like: $string = '!test'; preg_match('/^(!?)([a-z0-9]{1,10})(!?)$/i', $string, $matches); and examine $matches?...

regular expressions with escaping round brackets

php,regex,escaping,preg-match,brackets
I am trying to write the expresion that will accep fallowing phone numbers format: 508 736 756 505050505 +48 505 505 505 (+48) 505 505 505 ++48 505 505 505 (++48) 505 505 505 (23)692 36 99 23 692 36 99 I have wrote the fallowing expresion ^(([+]{0,2}?)?([+]{0,2}?)?([0-9 ]+)?)$ How...

Strip all hyperlinks that appear before the text (Wikipedia dump)

php,regex,preg-replace,preg-match,wikipedia-api
I am working on the wikipedia dump to find some useful information related to the first sentence that appeared on the first paragraph. The dump is highly unstructured as they have saved almost all of the information in one column. They use combination of symbols to recognize how the text...

Unknown modifier while using preg_quote() in preg_match_all()

php,preg-match,preg-match-all
I am having a problem with my preg_match_all() function. I have a string e.g. $string = '<div id="header">Hello</div>' preg_match_all('/'.preg_quote('<div id="header">').'(.*?)'.preg_quote('</end>').'/s', $string, $matches); And I am looking to get the output Hello. But I only get this error: preg_match_all(): Unknown modifier 'd' in C:\xampp\htdocs\classes\Functions.php on line 13 ...

Preg_match() usage with “{}” and “?”

php,regex,preg-match
I'm currently trying things with reggae (PCRE) and PhP. It seems that the function pre_match() does not work properly with the signs {} and ? and I'm wondering why. Can someone help me? Here is the code I'm using just for the example: <?php $search = "aaaah"; //Return "valid" while...

PHP preg_match to extract addresses from html code

php,preg-match
I am trying to extract the address and telephone number from HTML code. First I get the contents of the container member-address from the content of the page. preg_match('/id="member-addresses".*?<\/div>/is', $webpage, $contact_details); This returns this id="member-addresses"> <h2>Contact details</h2> <h3 id="foobar">Work</h3> <p> 123 Fake Street, Main Area, PG42 TGJ<br /> Tel: 020...

preg_match a specific content

php,regex,preg-match,preg-match-all
I'm really noob about regular expressions and I need a help. I tried lots of things but couldn't get the thing I need. <img src="http://img03.imgsinemalar.com/images/afis_buyuk/m/Maske.jpg" title="Maske (1994) afişi" alt="Maske (1994) afişi" itemprop="image" width="164" height="234"/> At this code src, title, alt, width and height can have various values. However, itemprop is...

Replace old eregi function PHP

php,preg-match,eregi
I'm having problems to fix this old PHP eregi funxtion becouse it uses IN parameter.. It's script for captcha generation class_log.php from Matthieu MARY old code: $sMotif = "--$sIN ([a-zA-Z0-9]{3,4},)*([a-zA-Z0-9]{3,4}){1}"; if ((eregi("$sMotif ",$this->sParam))||(eregi("$sMotif$",$this->sParam))){ $this->aParam['bExtension'] = TRUE; $this->aParam['aExtension'] = $this->_PARAM_get_extension($sIN); $this->aParam['inExtension'] = ($sIN=='e'); $this->aParam['iParameters']++; } I try with this, but not...

php function to search paths for filename WITHOUT extension

php,string,file,preg-match
Right so i'm making a configuration class that will use an array of different file types in 4 main locations. Now I want to make it so that the configuration class will search these locations in order at the moment i'm using the following if (file_exists(ROOT . DS . 'Application/Config/'...

preg_match checks on variable before submit

php,if-statement,preg-match
I need to make sure some checks are made before submitting a form: if ( preg_match( '/[^\d]/', $phone ) || (strlen( $phone ) < 11 ) ) The above statement checks that $phone is not less than 11 digits. I need to make extra checks. $phone must be 11 digits...

str_replace after preg_match hangs PHP

php,preg-match,str-replace
I am trying to retrieve a value from a returned header: HTTP/1.1 302 Moved Temporarily Date: Mon, 08 Jun 2015 00:48:51 GMT Server: Apache X-Powered-By: PHP/5.6.8 Expires: Thu, 19 Nov 1981 08:52:00 GMT Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Pragma: no-cache X-Frame-Options: SAMEORIGIN Set-Cookie: frontend=b09kg96q756cv2a08l9d6vbq07; expires=Mon, 08-Jun-2015 01:48:52 GMT; Max-Age=3600;...

RegExpre in PHP

php,regex,preg-match
I want search a 3 numbers (optional with decimal digit), I try using preg_match() in PHP, but that no filter using the regex /^\d{1,3}([,.]\d)?$/ input: 8631.0 output: array (size=2) 0 => string '368.6' (length=5) 1 => string '.6' (length=2)* ...

Regular Expression - Negation String + OR

php,regex,preg-match
I need to match string that are not 11111 OR 22222 (EXACT) <?php $string = 'STRING' $pattern = '#PATTER#' // what I have to find echo preg_match($pattern, $string) ? 'match' : 'no match'; Cases: $string = '33333';// match $string = '222222';// match $string = '11111';// no match $string = '22222';//...

remove a string with {{ xxx }} inside another string

regex,preg-match
This is a stupid question but I would like to remove {{Lien web ....}} (including brakets) inside a string. Example : test {{Lien web|xyz}} test {{xyz}} test Result should be : test test {{xyz}} test I tried with : preg_replace('/\{\{.*?\}\}\s*/s','',$string); but how to add "Lien web" ? Thanks a lot!...

Replace a particular character from a string from the x position of the character

php,string,replace,preg-replace,preg-match
I am having issue in replacing a particular character. Example 1: format : xxx-xxx-xxx if i enter 6953 in a field and hit submit i need the result like 000-006-953 Example 2: format : 1ax-xxx-xxx if i enter 6953 in a field and hit submit i need the result like...

How to get a substring until a specific character with preg_match in php?

php,regex,string,preg-match
Assuming I have these variations: 1: Today is a beautiful day (Monday) 2: Today is a beautiful day I want to get Today is a beautiful day. I'm trying preg_match('/(?=(^\w+.+))$|(?=(^\w+.+)\s\())/ui', $string, $matches) without success....

count repeated occurrence of 0 & 1 in a string

php,regex,preg-match
Return false if the repeated occurrence of 0's or 1's in the string is greater than number($k). I have written a function which works, but I need to optimize it: <?php function satisfied($str, $k){ $stream = $last = $str[0]; for($i = 1; $i <= strlen($str)-1; $i++){ if($str[$i] != $last) $last...

Allow whitespace, unicode letters, digits, underscore, dash AND comma?

php,regex,unicode,preg-match
I'm pretty new at the subject preg and I'm using this preg_match condition to check if the user has entered whitespace, unicode letters, digits, underscore or dash: if(preg_match("/[^\040\pL\pN_-]/u", $term)) { But now I wanted to allow a comma. So I tried this: if(preg_match("/[^\040\pL\pN,_-]/u", $term)) { And it actually works and...

PHP Regex Word Boundary exclude underscore _

php,regex,preg-match,underscores,word-boundary
I'm using regex word boundary \b, and I'm trying to match foo in the following $sentence but the result is not what I need, the underscore is killing me, I want underscore to be word boundary just like hyphen or space: $sentence = "foo_foo_foo foo-foo_foo"; X X X YES X...

PHP difficult preg_match

php,regex,preg-match
I'm trying to manage some files on my personal web server that I use for XBMC but all the files (Movies from YIFY) have names like Jumanji.1995-720p.YIFY.mp4 Silver.Linings.Playbook.2012.1080p.x264.YIFY.mp4 American Hustle (2013) 1080p BrRip x264 - YIFY.mp4 Notice that some of the items are separated with . and others with _...

Regex for a multiline string with PHP preg_match

php,regex,preg-match
I'm trying to build a pattern for a multiline string, that must start with <?php or whitespace + <?php and NOT end with ?> or ?> + whitespace. My attempt was /^\s?<\?php.*[^>]\s?$/s but it did not work. Also tried the negative lookahead - no use. Any idea? Thanks in advance....

CSV File import into the database with preg_match query for 400x400 contact url

php,mysql,preg-match,csv-import
My import script is working correctly. In $field_csv['imageUrlStr'] there are some different sized image urls, I need to fetch 400x400 string that contains the url for my image url, then insert that into the database, but when I am using my current code the same row gets inserted many times....

Breaking down a image url into three sub parts in PHP

php,regex,url,preg-match
Suppose I have this image URL: http://static2.tripoto.com/media/filter/medium/img/11099/TripDocument/chiang_mai_street_market.jpg I want to extract 3 things from this url: "medium" (This can be medium/small/thumbnail) the part after medium and before the image name (img/11099/TripDocument) image name (chiang_mai_street_market.jpg) ...

PHP: How can I make preg_match match only the first occurrence?

php,regex,preg-match
preg_match($pattern, $subject, $matches), $matches seems to be an array of all matches, I only need the first occurrence of the regex pattern, and I want the matching to stop right away once it finds a match and store it in $matches. Is it possible? Thank you. I'm not talking about...

preg_match_all with windows / macOS9 line endings

php,preg-match
I have the following code to create a little doxygen like public function parserAction () { $code = file_get_contents('/www/htdocs/rumpho/application/controllers/parserStr.php'); preg_match_all ( '/(private|public)?\s*function\s*(.*?)\s*\((.*?)\)\s*{(?:\n|\t|$)*(?:\/\*\*((?:\n|.|\t)*?)\*\/)?/msi', $code, $matches ); var_dump( $matches ); die; } it works when line endings of parserStr.php are encoded with unix but it doesn't work if the line endings are...

Regex - Exact match start to end

php,regex,preg-match
There seems to be a small confliction of my multi-line usage.. Here is the context test-test-3 test-1 I'm trying to regex exact match each line, Giving it the test string and it returns what after -: /test-(.*)/i This would catch 1st which is test-test-3, I want to catch the literal...

How to find total number of elements using regex

php,regex,preg-replace,preg-match,preg-match-all
Here is my problem I want to find the total number of <span> and </span> in the given paragraph The point is that it might contain <span id='someid'> or <span class='someclass'> And even like this This spanner is cool The only clue is that div will have < and >....

PHP preg_match() not working [duplicate]

php,preg-match
This question already has an answer here: “Unknown modifier 'g' in…” when using preg_match in PHP? 2 answers I have a script I wrote to scan several websites for a google link to make sure it is there. For some reason my script is not working. When I check...

Why is this PHP validation still setting the value

php,regex,validation,preg-match
I am trying to validate a form field (to be used for First Name) for letters and dashes only, but regardless of how I implement the code, the value of $player_name is still being set. if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["player_name"])) { $nameErr = "Name is required"; } else...

How to read a text file and search for a certain string before a colon and then show the content after the colon?

php,regex,file,preg-match,file-get-contents
I have a file that contains something like this: test:fOwimWPu0eSaNR8 test2:vogAqsfXpKzCfGr I would like to be able to search the file for say test and it set the string after the : to a variable so it can be displayed, used etc. Here is the code I have so far...

PHP preg_match not returning correct array

php,html,arrays,regex,preg-match
So I have been reading up on regex, I used a great tutorial on youtube that explained it very good and so I decided to try some using http://www.phpliveregex.com/ and it worked out great on the website but not in my php code. So what I want is to find...

preg_match name of input field inside form

php,forms,preg-match
Sorry, i spent like 2 hours trying to preg_match this form <form class="form-search" method="post" action="/index.php"> <div class="form-group"> <input id="address_box" type="text" class="form-control" name="x" value="" onfocus="this.select()" /> </div> <span class="btn btn-s btn-caps"><input type="submit" value="start" /></span> </form> To: Preg_match: START = <form WHERE action CONTAIN /index.php EX: action="/index.php" or action="http://whatever.com/index.php" FIND name="[A-Za-z]{1}" END...

PHP preg_match exclude

php,regex,preg-match,pcre,exclude
OK this regex will match string like 2aa, a2, 2aaaaaa, aaaa2, aaa2aaaa, 2222a2222-2222-aaaa... in short, mix of alphanumeric characters in a sequence: preg_match("/(?:\d+[a-z]|[a-z]+\d)[a-z\d]*/i") now I want to exclude something but I'm stuck, something like this doesn't work preg_match("/(?!1920x1200|1920x1080)(?:\d+[a-z]|[a-z]+\d)[a-z\d]*/i") for example the string aaaaa222aaa1920x1200bbbbb1234556789 is still matched but it shouldn't because...

Match all repeating occurrences regex

php,regex,preg-match
I need to match following string separated by whitespaces starting with "Token" . Example string Token token=12eqddsfasdsa [email protected] app_id=2312edsdas I have tried several expressions. ^Token (\w*=[^-\s]+) Captures only one first match. ^Token(\s\w*=[^-\s]+)+ This expression captures only last. I need to capture match[0] = token=12eqddsfasdsa match[1] = [email protected] match[2] = app_id=2312edsdas...

Regex matching multiple spaces/dashes in String

php,regex,preg-match
I have an input that has to be uppercase (with unicode support), and that can contain multiple spaces or dashes - (and that should start and end with letters). I have made this regex : /^[\p{Lu}]+\s*-*[\p{Lu}]+$/ As seen here, this matches everything I need unless it contains multiple dashes or...

PHP preg_match stops responding at certain number of characters in string

php,regex,preg-match
Is there some kind of PHP configuration setting that would affect the length of string being passed into preg_match or preg_match_all? I have the following which I am trying to test to work out what is going wrong for me: $re = "/\[\[section\:(.*?)\]\]((.|\n)*?)\[\[endsection\]\]/"; $str = "[[section:body]] lots of lines here...

preg_match zip code & state not working

php,preg-match
Not sure why the below is not finding zip and state? $str = 'contact_widget_statezip">NM&nbsp; 87035 '; $pattern = '[A-Z]{2}\W{1,10}[0-9]{5}'; preg_match_all($pattern, $str, $amatches); Thanks Glenn...

PHP - preg_match() word after other word

php,regex,preg-match
I have a text like this one: The cat was born on 1980 and lives ... So i want to get the cat's age with regex (the text could have more than 1 occurrence of a number with 4 digits). I'm trying this preg_match('/born on [0-9]{4}/', $text, $matches) but the...

Return 0 when regex match is found (PHP)

php,regex,range,preg-match,inverse
I am hoping to return 0 when 2011-2016 is found in the string. For the life of me I cannot figure out a regex that will return 0 when a match is found and 1 when there is no match. Yes I could easily negate the entire statement but I...

Regex is not working for some cases - PHP

php,regex,preg-match
I have a number of string patterns from which I filter out my data and insert it into a database. Now, I have to handle strings that my old regex is not able to match correctly. This is my regex: $re = "/(?:Expiration Fee: )?(\d+)\s+((?:[a-zA-Z0-9\/]+\s+)*)(?:\(([a-zA-Z]+)\)\s+)?(?:>([0-9.]+)\s+)?(?:(\d+-\d+)\s+)?(?:\((\d{1,2}(?::\d{2})?[AP]M)\)\s+)?(?:@\s+([\d.]+))/"; My complete code: $re =...

PHP regex matching id at the end of a string

php,regex,preg-match
I have a url like: http://abc.domain/path/path2/bla-bla-1456-327654-bla-bla-22222 I need some preg_match() witch will output "22222" Note: the number at the end of the string variates in size it could be "222" or "222222", before you mention reverse substr...

Changing preg_match condition

php,function,preg-match,vowel
My function is changing $word_one (je/que je in j'/que j'), if $word_two begins with a vowel. function FrenchCompoundTenses($word_one, $word_two) { if(preg_match('~(.*)\bje$~ui', $word_one, $m) && preg_match('~^[aeéiou]~ui>', $word_two)) return "<td class=\"text-right text-muted\">{$m[1]}j'</td>" . $word_two; else return "<td class=\"text-right text-muted\">". $word_one ."</td>" . $word_two; } For a similar function I have to change...

Seprate movie name and year from moviefile name

php,regex,preg-replace,preg-match
I have a file name like this Birdman.2014.DVDSCR.X264-PLAYNOW.mkv Divergent (2014) 720p Blu-Ray x2649 [Dual-Audio][English DD 5.1 + Hindi DD 5.1] - Mafiaking - TeamTNT ExClusive.mkv Cradle 2 The Grave 2003 HDTVRip 720p Dual-Audio[Eng+Hindi] ~ BRAR I have to seperated movie name and year For getting year in use perg_match like...

Match part of string with part of other string

php,regex,string,preg-match
I working on a simple search function where I want to match a part of a string with part of another string. Example: The search term is: fruitbag I want to match the product: fruit applebag I want to create something so that the system matches: fruitbag fruit applebag Or...

regex item count

php,regex,preg-match
I have two distinct styles of item count text to extract the total number of items from. From style 1 I need the number 3, From Style 2 i need 56 Style 1: 3 Item(s) Style 2: Items 1 to 45 of 56 total I was trying this to match...

preg_match with number PHP

php,regex,numbers,preg-match
When I use this : preg_match('/^[0-9]{1,10}(\.[0-9]{1,9})?$/', 0.0001); The return value is 1, and when I use this : preg_match('/^[0-9]{1,10}(\.[0-9]{1,9})?$/', 0.00001); The return value is 0. Somebody could say me why please ? Thanks !...