Search the Community
Showing results for tags 'regex'.
-
I have to pass the date in one of the step as current date and compare that, but failing to achieve that test case is "And the URL "<>" contains the following: "Measure name","Business description","Technical description","Data Sources",Reports,"Authored by","Last publish date" "First Test Measure","business Lorem Ipsum is simply","technical Lorem Ipsum is",CHRISS,First Test Report,, Here one of the parameter is "Last publish date" so I have to give it as it should be comes up as current date. I am trying to give the date [[now:j F Y], but it is not working. Below is the function written for it, what change I have to do so it can have the date as well. /** * Download a url and verify the contents. * * @throws \Exception * When the file contents don't match. * * @Then the URL :url contains the following: */ public function assertUrlContent(string $url, PyStringNode $content): void { $cookies = $this->getSession()->getDriver()->getWebDriverSession()->getCookie()[0]; $cookie = new SetCookie(); $cookie->setName($cookies['name']); $cookie->setValue($cookies['value']); $cookie->setDomain($cookies['domain']); $jar = new CookieJar(); $jar->setCookie($cookie); $client = new Client(); $res = $client->request('GET', $url, [ 'cookies' => $jar, 'verify' => FALSE, ]); $expected_string = preg_replace('/\r/', '', (string) $content); $actual_string = $res->getBody()->getContents(); if ($expected_string !== $actual_string) { print_r('Expected String: ' . PHP_EOL . $expected_string . PHP_EOL); print_r('Actual String: ' . PHP_EOL . $actual_string); throw new \Exception('Contents of download do not match'); } }
-
I am new to PHP, ereg_replace is deprecated so need to convert ereg_replace to preg_replace, I can't figure out how to put "delimiters and escape character" on $TEST_FILE below, can someone help me on this. function KernelBase(){ $i=0; $TEST_FILE="fdKernel/Init.php"; $TEST=$TEST_FILE; while(!file_exists($TEST)){ $TEST="../".$TEST; if($i>15) break; $i++; } return trim(ereg_replace($TEST_FILE,NULL,$TEST))."fdKernel/"; }
-
For right or wrong, I've been using XML to define my Doctrine entities. When the XML changes, my entities need to change. I've automated the process with a simple PHP script which allows me to swap some text to modify one of the auto-generated methods, add methods, etc. Kind of clunky but it works well enough. Now, I recently had the need to remove a given method in its entirety from a given class. I "could" just add the entire string which represents the method name, earlier comments, and script for the method to my parsing script to my parsing script and remove it, but would like to be a little more concise. For instance, say I have $script as follows: $script = <<<'EOT' class SomeEntityClass { //... more stuff above public function getSomething() { return $this->something; } /** * Get foos. * * @return \Doctrine\Common\Collections\Collection */ public function getFoos() { return $this->foos; } /** * Get somethingElse. * */ //... more stuff below } EOT; How would you recommend creating the function: removeFunction($script, 'getFoos') which would remove the given function along with its comments from the $script string and result with? $script = <<<'EOT' class SomeEntityClass { //... more stuff above public function getSomething() { return $this->something; } /** * Get somethingElse. * */ //... more stuff below } EOT; Assuming regex is the way to go, I was thinking of something like the following, but could use some help with the regex expression. function removeFunction($script, $method) { $method="public function $method("; //regex to remove script with which starts after pattern "{\n" OR "**/", contains $method, and is located before pattern "\n{" OR "\n /**" return $script; } Thanks
-
Hi all, I want to know if it's possible that the regex matches for the exact subject string, instead of checking for the match anywhere inside of a string. to take an example, if the regex is /([A-z0-9])\w+\.\w{3,4}/ and the subject string is , (i.e. the one within the double quotes.) "'sjvjhvbj.bnm'lsjksnkboubouboubsoubsobob.txt" then because the string begin's with a single quote, it should return a mismatch. That is what I would like to achieve. What is happening is that it finds a pattern match inside the string as : sjvjhvbj.bnm which is not what is desired. Thanks all !
-
this is my code $re = '/[^\W][a-zA-Z\d.-]{3,20}/'; if(!preg_match_all($re, $username)){ do something }else{ do somthing else } $username is a $_POST['username']; when i submit a 3 letter word it works but when i use symbols like $ and ! and etc it still goes through, im trying to get a regex where the username is 4-20 characters long and only the alphabet and numbers and dots and dash but dots and dashs cant be next to each other thx
-
I have a file in the same location as my PHP file, say test.txt, and in multiple locations it has content like: - href="http://www.domain.com/entry.php/256/1/this-is-the-title" or href="http://www.domain.com/entry.php/123/2/another-title" which I need replaced within the file to: - href="{EntryNumber=256.link}" and href="{EntryNumber=123.link}" Only the first number is needed for the replacement, it will be between 1 and 999. Everything between the 5th / and the 2nd " can be safely ignored and removed. This is not the only content in the line, and sometimes there may be more than one occurrence per line. I've got this so far: - $buffer = ""; $fp = file($file); foreach($fp as $line){ $buffer .= preg_replace(***struggling with this bit***); } fclose($fp); echo $buffer; file_put_contents($file, $buffer); Am I along the right lines generally? And I have no idea what the preg_replace should be as my regex is a bit trial and error, more error in this case... As always, any help greatly appreciated! EDIT: If it matters, the largest file I need to edit is 39Kb, and includes 175 occurrences of the replacements.
- 4 replies
-
- preg_replace
- file
-
(and 1 more)
Tagged with:
-
I suck at Regex. Can someone tell me the PHP regex check to see if a string is 12345-6789 .... meaning, five digits, a dash, and then four digits? I'm sure it's quite simple for a Regex pro. Thank you.
-
i have this link Stottoma-BC-textiles/first-bale/-t6/-c2/ and this regex RewriteRule ^.*-([a-z]+)/-t([0-9]+)/-c([0-9]+)/?$ /index.php?Page=$1&baleId=$2&CategoryId=$3 [L] where am going wrong with the regex iam getting not found error
-
I have a regex expression that validates a set of mobile numbers: The numbers have optional prefixes (+234 or 234 or 0) and I have used the alternation with the pipe character. Immediately following the international code or zero character is a set of service provider specific identifiers that I have also specified the options using the alternation character. Based on the regex I have, this number should not be valid (12349098766543); but the regex returns it as valid. It appears the there is a match on 909 in the code. But shouldn't the presence of 1 at the beginning of the test string enforce a validation failure? What is wrong with the regex i have here? function check_number($number) { if(!preg_match('/[+234|234|0]?(704|702|803|806|703|706|813|816|810|814|903|802|708|808|812|701|902|809|817|818|909|908|805|705|815|807|811|905)\d{7}$/', $number)) { return 'Invalid Phone Number'; }else{ return 'valid Phone Number';} The execution below should fail, but is is passed as valid. $str = '12349098766543'; echo check_number($str);
-
When I read HTML source of below link http://www.dresslink.com/women-candy-color-handbag-leather-cross-body-shoulder-bag-bucket-bag-p-10908.html I can find below data about the product: <script type="text/javascript"> item.stock['ss42356']=[]; DL.item.stock['ss42356']['qty']=56; DL.item.stock['ss42356']['sku']='SV000837_B'; DL.item.stock['ss42356']['inexistence']=0; DL.item.stock['ss42356']['down_shelf']=0; DL.item.stock['ss42356']['procurement_cycle']='8'; DL.item.stock['ss42356']['paid_set']=[]; DL.item.stock['ss42356']['paid_set'].push(35630); DL.item.color_image['35630']='of7ea7'; DL.item.stock['ss42357']=[]; DL.item.stock['ss42357']['qty']=29; DL.item.stock['ss42357']['sku']='SV000837_G'; DL.item.stock['ss42357']['inexistence']=0; DL.item.stock['ss42357']['down_shelf']=0; DL.item.stock['ss42357']['procurement_cycle']='6'; DL.item.stock['ss42357']['paid_set']=[]; DL.item.stock['ss42357']['paid_set'].push(35631); DL.item.color_image['35631']='of710e'; DL.item.stock['ss42358']=[]; DL.item.stock['ss42358']['qty']=14; DL.item.stock['ss42358']['sku']='SV000837_BR'; DL.item.stock['ss42358']['inexistence']=0; DL.item.stock['ss42358']['down_shelf']=0; DL.item.stock['ss42358']['procurement_cycle']='17'; DL.item.stock['ss42358']['paid_set']=[]; DL.item.stock['ss42358']['paid_set'].push(35632); DL.item.color_image['35632']='of77c1'; DL.item.stock['ss42359']=[]; DL.item.stock['ss42359']['qty']=36; DL.item.stock['ss42359']['sku']='SV000837_O'; DL.item.stock['ss42359']['inexistence']=0; DL.item.stock['ss42359']['down_shelf']=0; DL.item.stock['ss42359']['procurement_cycle']='7'; DL.item.stock['ss42359']['paid_set']=[]; DL.item.stock['ss42359']['paid_set'].push(35633); DL.item.color_image['35633']='of7136'; </script> I need to know the quantity for each SKU, so I need to produce a simple array containing each SKU name and it's quantity like below $a = array( 'SV000837_B' => '56', 'SV000837_G' => '29', 'SV000837_BR' => '14', 'SV000837_O' => '36', ); Please help me write a PHP code using regex and any other method to provide above array.
-
hello every body, Currently i'm scraping web data for a demo project but i cant preg_match the value from this html. The html code is <div class="carouselContainer leftDisabled"> <ul class="carousel leftDisabled"> <li> <div class="thumbContainer"> <div class="thumb" style="background-image:url(http://img6a.flixcart.com/image/mobile/v/h/g/samsung-galaxy-core-2-sm-g355h-100x100-imadzb4ywyj25mw4.jpeg)" data-imageId="IMADZB4YWYJ25MW4"> </div> </div> </li> <li> <div class="thumbContainer"> <div class="thumb" style="background-image:url(http://img6a.flixcart.com/image/mobile/v/h/g/samsung-galaxy-core-2-sm-g355h-100x100-imadzb4zhk4855ny.jpeg)" data-imageId="IMADZB4ZHK4855NY"> </div> </div> </li> <li> <div class="thumbContainer"> <div class="thumb" style="background-image:url(http://img6a.flixcart.com/image/mobile/v/h/g/samsung-galaxy-core-2-sm-g355h-100x100-imadzwrpmdwhnxg7.jpeg)" data-imageId="IMADZWRPMDWHNXG7"> </div> </div> </li> <li> <div class="thumbContainer"> <div class="thumb" style="background-image:url(http://img6a.flixcart.com/image/mobile/v/h/g/samsung-galaxy-core-2-sm-g355h-100x100-imadzwvvz3deeh4c.jpeg)" data-imageId="IMADZWVVZ3DEEH4C"> </div> </div> </li> </ul> </div> The regex i've used is preg_match_all('|<div class="carouselContainer leftDisabled"+>(.*)</div+>|U',$txt,$matches3); I want only the images images url from that specific block. Can anybody help me in this plz...
-
Could anybody please give me a regex for numbers and dashes only? Thanks
-
First time post, be easy on me... I'm using preg_match_all to return an array with all the matches. I know I'm missing something fundamental, but I either keep looking past it or am more screwy than I know. Sample String CC-BY-ND-NC I'm using the following code preg_match_all("/cc|creative commons|copyright|by|sa|nc|nd/i",$exifmeta['copyright'],$cmeta) I would expect to see Array ( [0] => Array ( [0] => CC [1] => BY [2] => ND [3] => NC ) ) What I get is Array ( [0] => Array ( [0] => CC [1] => BY [2] => ND [3] => NC [4] => sa ) )
-
I have a PHP comments filtration/validation script incorporated into my PHP/mysql custom built blog (under development). This script uses REGEX to evaluate the format of user created comments. This function is supposed to accomplish the following tasks: All code except those in the whitelist must be wrapped in the permitted bbcode tags. The bbcode tags can not be empty The bbcode tags must be used in pairs other forms of bbcode tag must be rejected except if wrapped in the permitted bbcode tag user can not post only code, some descriptive text must be added to explain code. this text can be before or after the code. posted comment string must satisfy minimum and maximum length criteria I shall provide the developer with my current PHP script so he may understand how to lay the script out. If your are good at REGEX, contact me. Thanks.
-
I have a regex that validates a string. I want to ensure there is no space in the string. Thus far I have used the negative look ahead regex construct as shown below to match strings without spaces. (?!.*(\s)) While this prevents space in between a word, all strings with space characters at the end or beginning are getting validated. I do not want that at all. This is the full regex script below: $string = "#JebiamgoOeing0"; if (preg_match('/^.*(?=.{8,})(?!.*([A-Za-z0-9])\1{1})(?=.*[a-z])(?=.*[A-Z])(?!.*(\s))(?=.*[\d])(?=.*[\W]).*$/', $string)) { "do something"; } else { "do something else"; } I need help in resolving this. Thank you.
-
how to take a word in php or explode based on luas Bangunan :xxx For example I have string $string =" Kondisi Properti : Bagus Dilengkapi Perabotan : Unfurnished Sertifikat : Lainnya Daya Listrik : 2200 Watt Kamar Tidur : 3/1 Kamar Mandi : 2/1 Luas Bangunan : 92 m² Luas Tanah : 126 m² Jumlah Lantai : - Kondisi Properti : Bagus Sekali Dilengkapi Perabotan : Unfurnished Sertifikat : SHM - Sertifikat Hak Milik Daya Listrik : 6600 Watt Saluran Telepon : 1 Garasi : 3 Kamar Tidur : 4/1 Kamar Mandi : 3/1 Luas Bangunan : 300 m² Luas Tanah : 228 m² Jumlah Lantai : 2.5 "; eg I want to take every "Luas bangunan: xxx" Thanks
- 5 replies
-
- explode based on string
- regex
-
(and 3 more)
Tagged with:
-
I thought this should be a very trivial issue but I was wrong. I have a name filteration function below that checks user input for: empty string, regex pattern, length of string In using the function ro check user input, I am using the elseif logic function as shown below. I think the 'elseif conditional expression evaluates to TRUE' ( returning my custom error code 100) , when it should not, or am I missing something?? function CheckFullname($string, $maxlen, $minlen) { /* define error codes 100 = wrong pattern match 101 = string is too long 102 = string is too short 0 = empty input */ // now we see if there is anything in the string if ($string = '') { return 0; } // then we check fullname format elseif (!preg_match('/^(?:[\p{L}\p{Mn}\p{Pd}\'\x{2019}]+\s[\p{L}\p{Mn}\p{Pd}\'\x{2019}]+\s?)+$/u', $string)) { return 100; } //how long the string is elseif (strlen($string) > $maxlen) { return 101; } // how short the string is elseif (strlen($string) < $minlen) { return 102; } else { // if all is not well, we return true return true; } } // this function executed below is returning error code 100. $string = "John Doe"; if(Checkfullname($string, 40, 4)== 0) { echo 'Your name is required.'; } elseif(Checkfullname($string, 40, 4) == 100) { echo 'Please provide your full name without any funny characters.'; } elseif(Checkfullname($string, 40, 4)== 101) { echo 'Your name should be at most 40 characters long.'; } elseif(Checkfullname($string, 40, 4)== 102) { echo 'Your name should be at least 4 characters long.'; } else { $fullname = safe($string); }
-
Is there a difference between a single quote regex and and double quote regex ? for example : <?php $res1 = preg_match('/shi*t/', $comment); $res2 = preg_match("/shi*t/", $comment); ?> Thank you
-
While using the PHP strip_tags() function,I used the optional second parameter to specify tags which should not be stripped. However with these allowable_tags, I realised strip-tags is not safe. for example with a string such as this ($str= "<p onmouseover=\"evilscript url\"> Hi, this is an interesting link. </p>") I was able to load a page containing a script injected into it, that script was able to rip off my session cookie ID!!!. To further strengthen data sanitization using the strip_tags() function, I have come up with this function below which does the following: allows the use of the following html tags: <h1><h2><h3><h4><h5><h6><a><br><table><ul><ol><li><p><img> remove classes, ids from html tags remove font-style, font-size, color,font-family,line-height from style tags in the text; remove javascript attributes within a tag remove empty style tags function CleanUp($InputString) { $RemoveAttrib = "'\\s(class|id|javascript:|onclick|ondblclick|onmousedown|onmouseup|onmouseover|onmousemove|onmouseout|onkeypress|onkeydown|onkeyup)=\"(.*?)\"'i"; //remove classes, ids and disallow these attributes/prefix within a tag; $InputString = strip_tags($InputString, '<h1><h2><h3><h4><h5><h6><a><br><table><ul><ol><li><p><img>'); $InputString = preg_replace($RemoveAttrib, '', $InputString); $RemoveAttrib = "/(font\-size|color|font\-family|line\-height):\\s". "(\\d+(\\x2E\\d+\\w+|\\W)|\\w+)(;|)(\\s|)/i"; //remove font-style, font-size, color,font-family,line-height from style tags in the text; //$InputString = stripslashes($tagSource); $InputString = preg_replace($RemoveAttrib, '', $InputString); $InputString = str_replace(" style=\"\"", '', $InputString); //remove empty style tags, after the preg_replace above (style=""); return $InputString; } This worked well for single line text, but if I had hard returns in the text the function could not find the other tags to remove, and therefore failed. See below. <p id= "mike" style="line-height: 150%; class="lead">The function did not strip off the paragragh ID attribute.</p> Or <p id ="mike" style="line-height: 150%; class="lead">The function did not strip off the paragragh ID attribute.</p> I tried marching New lines as shown below but it did not work: $RemoveAttrib = "'\\s(class|id|javascript:|onclick|ondblclick|onmousedown|onmouseup|onmouseover|onmousemove|onmouseout|onkeypress|onkeydown|onkeyup)(\r\n)*?=\"(\r\n)*?(.*?)\"'i"; I need help to fix this. Thanks.
- 2 replies
-
- php
- strip_tags()
-
(and 1 more)
Tagged with:
-
Hi people, i need to find 16x150gr in Dried Pomegranate Arils16x150gr but the format can vary from Mt Ceder Balsamic Vinegar 12x250ml to Mt Ceder Balsamic Vinegar 2x2ltr to Dried Kalamata Olives 4x1kg. i guess you got the drift i tried something like : '/[1-9]+x[1-9]+[a-z]+/' but i am so useless at regex. Thank you!
-
This is my preg_match code: preg_match("/(\d+)|(T)|(A)/", $link, $matches, PREG_OFFSET_CAPTURE, ($off-30) It works and matches the number I want, except it only returns the first character in the $matches array. For instance, if the number it finds is 10, it only returns 1. Now I understand that is what preg_match does, but how would I make that regex ungreedy? I tried adding a *, but it just made an error, and preg match all would keep searching for strings after the first one. All I want is for the first number, regardless of the length of it, to be returned in full. Thanks for any help.
- 1 reply
-
- regex
- preg_match
-
(and 1 more)
Tagged with:
-
I have a CSV file which has more than 50k records and i want to convert this using regex Item Code,,Qty CMAC-389109,,6 ,Serial No., ,954zg5, ,ffnaw8, ,gh8731, ,gxj419, ,hc6y9q, ,y65vh8, CMAC-394140,,1 ,Serial No., ,4cu3z7, and I want to convert this data to below format: ItemCode,Serial Number,Qty CMAC-389109,"954zg5, ffnaw8, gh8731, gxj419, hc6y9q, y65vh8",6 CMBM-394140,"4cu3z7",1 Can i achieve this using find and replacement ? Any help will be highly appreciated.
-
Hi, I'm trying to retrieve the integer value between the <span> tag from a HTML source code. HTML source code: <span> (3861822) </span> This is the php code: <!DOCTYPE html> <html> <body> <?php //use curl to get html content function getHTML($url,$timeout) { $ch = curl_init($url); // initialize curl with given url curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]); // set useragent curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // write the response to a variable curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // follow redirects if any curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); // max. seconds to execute curl_setopt($ch, CURLOPT_FAILONERROR, 1); // stop when it encounters an error return @curl_exec($ch); } $html=getHTML("http://www.alibaba.com/Products",10); preg_match("/<span>(.*)<\/span>/i", $html, $match); $title = $match[1]; echo $title; ?> </body> </html> Whenever I try to run it, this error will come out: Notice: Undefined offset: 1 in C:\xampp\htdocs\myPHP\index.php on line 19. How to correct it so that it will display all the integer value within the tag name but without the bracket? Thanks
-
I need to match n occurrences of "." in a string following specific rules. The number of occurrences found by the regex should correspond with the exact amount of "."'s in the string. The rules are: 1) every "." must be preceded by at least one digit from 1-9, and can be preceded by up to two other digits from 0-9 (basically, values from 1-999) 2) every "." must be followed by at least one digit from 1-9, and can be followed by up to two other digits from 0-9 (again, values from 1-999). Sample valid strings are: 1) "1.3.5.7.9" 2) "21.23.25.27.29" Sample invalid strings are: 1)"01.5.7.9" (first digit of the number preceding the dot cannot be a zero) 2) "1.05.7.9" (first digit of the number preceding or following the dot cannot be a zero) 3) "1.5.7777.9999" (cannot have more than 1 digit with value 1-9 and up to two more digits with value 0-9 (so up to 3 digit numbers); here we have four digit numbers) I'm using preg_match_all to match all occurrences of the dot in the string, and I'm using lookaheads seeing that the digits matched are shared between the dots (the same digit that is preceding a dot is following another dot). The problem is, when I have two or three digit numbers, I'm getting more matches than I need. Here is my pattern: /(?=([1-9][0-9]{0,2}\.[1-9][0-9]{0,2}))/ Here is my test subject: "Mt1,1-15.17.19" There are only two dots, but I am getting four matches: array ( 0 => array ( 0 => '', 1 => '', 2 => '', 3 => '', ), 1 => array ( 0 => '15.17', 1 => '5.17', 2 => '17.19', 3 => '7.19', ), ) I would like to get only two matches ('15.17' and '17.19'), as many matches as there are dots that fall within the rules but no more. <?php $string = "Mt1,15.17.19"; if(preg_match_all("/(?=([1-9][0-9]{0,2}\.[1-9][0-9]{0,2}))/",$string ) != substr_count($string ,".") ){ echo "There are ".substr_count($string ,".")." dots in this string, but there are ".preg_match_all("/(?=([1-9][0-9]{0,2}\.[1-9][0-9]{0,2}))/",$string )." valid occurrences of the dot!"; } ?> Since there can't logically be more valid occurrences than actual occurrences, for the time being I'm just using a "less than" operator instead of a "not equals" operator. But I would like to learn how to get a regex pattern that matches the exact amount of valid instances.
- 4 replies
-
- preg_match_all
- lookahead
-
(and 3 more)
Tagged with:
-
For a very 'loose' email address validator, does the following regex need the backslash before the dot? ^\S+@\S+\.\S+$ (Checks for anything@anything.anything but I'm gonna change that to anything.anything to make it even 'looser') I tested with and without the backslash using rubular.com and it seems superfluous but I'd like a second opinion or two please. ALSO: does rubular.com use the right engine to be correct for php? I hope so coz it's the first time I've been able to fully understand some regexes I've been blindly implementing for some time! Many thanks in advance