Jump to content

Search the Community

Showing results for tags 'regex'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Welcome to PHP Freaks
    • Announcements
    • Introductions
  • PHP Coding
    • PHP Coding Help
    • Regex Help
    • Third Party Scripts
    • FAQ/Code Snippet Repository
  • SQL / Database
    • MySQL Help
    • PostgreSQL
    • Microsoft SQL - MSSQL
    • Other RDBMS and SQL dialects
  • Client Side
    • HTML Help
    • CSS Help
    • Javascript Help
    • Other
  • Applications and Frameworks
    • Applications
    • Frameworks
    • Other Libraries
  • Web Server Administration
    • PHP Installation and Configuration
    • Linux
    • Apache HTTP Server
    • Microsoft IIS
    • Other Web Server Software
  • Other
    • Application Design
    • Other Programming Languages
    • Editor Help (PhpStorm, VS Code, etc)
    • Website Critique
    • Beta Test Your Stuff!
  • Freelance, Contracts, Employment, etc.
    • Services Offered
    • Job Offerings
  • General Discussion
    • PHPFreaks.com Website Feedback
    • Miscellaneous

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


Location


Interests


Age


Donation Link

  1. The bbcode below is not parsing code on multiple lines or recognizing line breaks, except the full content code is on one line. <?php function bbcode2html($var) { // code synthax highlighter $var = preg_replace('/\[code](.+?)\[\/code]/i', '<pre><code>$1</code></pre>', $var); return $var; } $content= '[code] <!DOCTYPE html> [/code]'; echo $content= bbcode2html($content); ?> I attempted introducing a new line recognition character into the regex as shown below, but its not working. <?php function bbcode2html($var) { // code synthax highlighter $var = preg_replace('/\[code]\r\n(.+?)\[\/code]/i', '<pre><code>$1</code></pre>', $var); return $var; } $content= '[code] <!DOCTYPE html> [/code]'; echo $content= bbcode2html($content); ?> I would appreciate your suggestions. Thanks.
  2. Hi, I was wondering if some kind person could help me with this. I need to make a call to file under linux that returns various SMART HDD data. From that file I want to see that each line ends in OK. I also want to extract the HDD Temperature from a line with a specific identifier on it. Filename = get_hd_smartinfo -d1 Response = 001 Raw_Read_Error_Rate 0 100 100 016 OK 002 Throughput_Performance 0 100 100 054 OK 003 Spin_Up_Time 321 (Average 164) 237 237 024 OK 004 Start_Stop_Count 6286 099 099 000 OK 005 Reallocated_Sector_Ct 0 100 100 005 OK 007 Seek_Error_Rate 0 100 100 067 OK 008 Seek_Time_Performance 0 100 100 020 OK 009 Power_On_Hours 30115 096 096 000 OK 010 Spin_Retry_Count 0 100 100 060 OK 012 Power_Cycle_Count 81 100 100 000 OK 192 Power-Off_Retract_Count 7535 094 094 000 OK 193 Load_Cycle_Count 7535 094 094 000 OK 194 Temperature_Celsius 42 142 142 000 OK 196 Reallocated_Event_Count 0 100 100 000 OK 197 Current_Pending_Sector 0 100 100 000 OK 198 Offline_Uncorrectable 0 100 100 000 OK 199 UDMA_CRC_Error_Count 0 200 200 000 OK Line = 194 Temperature_Celsius Value I want to capture = 42 in this case. I am sure there is an easier way than my tired old brain suggests, which is to output to a file, read file, grab line then somehow grab value, in a huge block of code. Thanks to anyone who can help me out. Kind regards, jB
  3. hi there everyone! i currently have, in my php document (which generates various xml depending on post and querystring request values) - the following function: function getdbconfig($file = "") { if ($_GLOBALS["ssl_enabled"] == 1 && ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) || $_GLOBALS["ssl_enabled"] == 0) { $pattern = '/^\$conn = mysql_connect\("([a-zA-Z._0-9\-]+)", "([a-zA-Z_0-9]+)", "([a-zA-Z_0-9]+)"\);$'. '|^mysql_select_db\("([a-zA-Z_0-9]+)", \$conn\);$'. '|^date_default_timezone_set\([\'"]([A-Za-z0-9\/+\-]+)[\'"]\);$'. '|^\$GLOBALS\["dtmstyle"\] = "([^"]+)";$'. '|^\$GLOBALS\["dtlast"\] = ([0|1]);$'. '|^\$GLOBALS\["prod_prodmode"\] = ([0|1]);$'. '|^\$GLOBALS\["prod_prodmail"\] = "([^@]+@[^"]+)";$'. '|^\$GLOBALS\["curl"\] = ([0|1]);$'. '|^\$GLOBALS\["conn_timeout"\] = ([0-9]+);$'. '|^\$GLOBALS\["post_timeout"\] = ([0-9]+);$'. '|^\$GLOBALS\["ssl_enabled"\] = ([0|1]);$/m'; $connstr = file_get_contents($file, FILE_USE_INCLUDE_PATH); echo "<sql>".$connstr."</sql>\n"; $arr = array(); if (preg_match_all($pattern,$connstr,$arr,PREG_PATTERN_ORDER)) { echo "<sql>".print_r($arr,true)."</sql>\n"; array_push($GLOBALS["sql"],print_r($arr,true)); echo " <conn dbsrvr=\"".$arr[1][6]."\" dbname=\"".$arr[4][7]."\" user=\"".$arr[2][6]."\" pass=\"".$arr[3][6]."\" php_tz=\"".$arr[5][10]."\" php_dtf=\"".$arr[6][8]."\" php_dta=\"".$arr[7][9]."\" pt_on=\"".$arr[8][0]."\" pt_mail=\"".$arr[9][1]."\" curl=\"".$arr[10][2]."\" cto=\"".$arr[11][3]."\" pto=\"".$arr[12][4]."\" ssl=\"".$arr[13][5]."\" />\n"; } } else { $redirect = "https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; header("Location: $redirect"); } } however - there is something wrong somewhere in the outer if statements, as i get nothing printed! the global variables should post the following, according to the currently parsed file contents: <?xml version="1.0" encoding="utf-8"?> <root> <conn dbsrvr="localhost" dbname="*****" user="*****" pass="*****" php_tz="Africa/Johannesburg" php_dtf="Y/m/d H:i:s" php_dta="0" pt_on="0" pt_mail="greywacke@outlook.com" curl="1" cto="15" pto="30" ssl="0" /> <sql></sql> </root> please note - private information such as database names, usernames and passwords were replaced with ***** can anyone help me out please, in resolving this issue? (to get the regular expression values printed!) any comments, questions and/or suggestions are welcome! sincerely, Pierre du Toit.
  4. Ok I am a complete noob!!! I have done many searches and believe that I have done quite well some what piecing together my script. So I use a forum which has a gear swap section for buying used goods problem is that if you try to search for specific goods then it searches the entire forum. So I found the simple_html_dom class that has the file_get_html method and was able to select only the titles of the listings. I had no problem displaying these listings and then populating a db. Now I want to use if and else-if statements along with regex to grab titles with specific keywords and put them in a corresponding column in my db which I have been unsuccessful at. I'd also like to eventually make my db searchable on my site I'm sure my code could be cleaned up in about every area so if anybody whats to chime in on any part of my code please feel free. It will be much appreciated I have put in many hours and I would like to know that building someone on the right footing lol. you can view my webpage at http://php-ryanlitwiller.rhcloud.com/ - in my page the titles still have their hyperlink but they try to navigate my server...any ideas of how to make them reach the original site? <?php // Open a MySQL connection $link = mysql_connect('127.6.146.130:3306', 'xxxxxxxxxx', 'xxxxxxxxxx'); if(!$link) { die('Connection failed: ' . mysql_error()); } // Select the database to work with $db = mysql_select_db('test'); if(!$db) { die('Selected database unavailable: ' . mysql_error()); } // import simple_html_dom.php to give me various methods for website selection and scraping include('simple_html_dom.php'); // get DOM from BPL URL $html = file_get_html('http://www.backpackinglight.com/cgi-bin/backpackinglight/forums/display_forum.html?forum=19'); // find all td tags with class=forum_listing foreach($html->find('td.forum_listing') as $tdTagExt) //grab just a tags foreach($tdTagExt->find('a')as $aTagExt){ //print selected outertext from previous selectors $refinedTitle = $tdTagExt->outertext; //display nobull listing of goods echo $refinedTitle . '<br>'; //find tent goods using regex to check for the word tent if(preg_match_all('/tent/', $refinedTitle)){ // add matches to corresponding sql coulom $sql = "insert into `bp` (`tent`) values ('$refinedTitle')"; $result = mysql_query($sql); //find sleeping bags using regex to check for the word bag } else if(preg_match_all('/bag/', $refinedTitle)){ $sql1 = "insert into `bp` (`bag`) values ('$refinedTitle')"; $result1 = mysql_query($sql1); //find boots using regex to check for the word boot or shoes } else if(preg_match_all('/boot|shoes/', $aTagExt->innertext)){ $sql2 = "insert into `bp` (`boot`) values ('$aTagExt->innertext')"; $result2 = mysql_query($sql2); //find clothing goods using regex to check for any of the words shirt|pants|parka|shorts|jacket } else if(preg_match_all('/shirt|pants|parka|shorts|jacket/', $aTagExt->innertext)){ $sql3 = "insert into `bp` (`clothing`) values ('$aTagExt->innertext')"; $result3 = mysql_query($sql3); } else { // Create and execute a MySQL query $sql4 = "insert into `bp` (`ahref`) values ('$aTagExt->innertext')"; $result4 = mysql_query($sql4); } } // Close the connection mysql_close($link); ?>
  5. Hey guys. I have a string like this: <before>http://www.soundcloud.com/artist/track<after> <before>www.facebook.com/page<after> <before>www.youtube.com/watch?v=1234567<after> <before>www.somesite.com/bla<after> I created this RegEx to find and replace URLs with preg_replace ((https?:\/\/)(www\.)|(https?:\/\/)|(www\.))[^ <]+ ...but how I extend that RegEx to match all URLs which are NOT Youtube or Soundcloud URLs. Thanx for helping. Mat
  6. Hi Guys, So I am trying to figure out how I can an input such as [url=value] and turn it into <a href="value"> Of course, I want to preserve that value. Thanks for the help!
  7. I'm quite new to regular expressions and i looked through all the asked questions and unfortunately couldn't find any answer.. I want to extract a specific parts of my website and simply echo them to a new page. My list of categories is structured alphabeticlly like this - <a href="architecture.html">ARCHITECTURE</a><br /> <a href="art.html">ART</a><br /> <a href="avantgarde.html">AVANTGARDE</a><br /> . . . and so on. now, what i'm trying to actually do is to extract all the categories as a plain text and simply echo them on the screen. (in this case i need to extract every string that starts with ">A and ends with </a (assuming i dont have any other similiar pattern within my code). i found this piece of code actualy in stackoverflow that supposed to extract anything that exists between tags, but unfortunately it's not the case.. html part - <div name="changeable_text">**GET THIS TEXT**</div> php part - $categories = file_get_contents( $url); libxml_use_internal_errors( true); $doc = new DOMDocument; $doc->loadHTML( $categories); $xpath = new DOMXpath( $doc); $node = $xpath->query( '//div[@name=changeable_text]')->item( 0); echo $node->textContent; // This will print **GET THIS TEXT**
  8. I have problem creating patern with preg_match_all and add it to array, its involved json data, Ch0cu3r helped me alot with my previous question http://forums.phpfreaks.com/topic/285059-preg-match-all-problem/, maybe he is still around? VI.data.aurora.idx = {140108: {act: 3, sun: ['s0','16:00','11:08','17:12','09:56'], moon: ['7','t3','03:51','']}, 140109: {act: 2, sun: ['s0','16:02','11:06','17:14','09:55'], moon: ['8','t3','05:12','']}, 140110: {act: 2, sun: ['s0','16:05','11:04','17:16','09:54'], moon: ['9','t3','06:28','']}, 140111: {act: 3, sun: ['s0','16:08','11:02','17:18','09:52'], moon: ['10','t3','07:35','']}, 140112: {act: 2, sun: ['s0','16:11','11:00','17:20','09:51'], moon: ['11','t3','08:30','']}, 140113: {act: 2, sun: ['s0','16:14','10:57','17:23','09:49'], moon: ['12','t3','09:11','']}, 140114: {act: 2, sun: ['s0','16:17','10:55','17:25','09:48'], moon: ['13','t3','09:41','']}, 140115: {act: 2, sun: ['s0','16:20','10:53','17:27','09:46'], moon: ['14','t4','16:33','10:03']}, 140116: {act: 2, sun: ['s0','16:23','10:50','17:30','09:44'], moon: ['15','t4','17:46','10:18']}, 140117: {act: 2, sun: ['s0','16:26','10:48','17:32','09:42'], moon: ['16','t4','19:03','10:30']}}
  9. I have the following string : 't':new Date(2014,1-1,3,9,35,38),'a':'3.57289','lat':'12,123','lon':'-12,123','dep':'1,1','s':'1,0','q':'90,02','dL':'4,3','dD':'VSV','dR':'PlaceName' t=date and time a=? lat=latitude lon=longitude dep=depth s=magnitude q=quality dL=? dD=direction dR=PlaceName I am trying to get the data into array with preg_match_all Can anyone help me out?
  10. Hi this is my first post after registering here. Please help me. I have a string of user data comma separated as below and pipe separated.I have been trying to remove duplicates by converting it to array. And even with php But it all does not works. My data looks like below: Marja_Roxburgh|abc@abc.com|123-456-7890|N/A|2011-11-17|N/A|N/A|N/A|N/A|N/A|120, Santa_Roxburgh|bmw@abc.com|123-456-7890|N/A|2013-11-17|N/A|N/A|N/A|N/A|N/A|10, Marja_Roxburgh|abc@abc.com|123-456-7890|N/A|201-11-17|N/A|N/A|N/A|N/A|N/A|300, Saga_Shera|xyz@abc.com|123-456-7890|N/A|2013-11-17|N/A|N/A|N/A|N/A|N/A|0, Marja_Roxburgh|abc@abc.com|123-456-7890|N/A|2013-11-17|N/A|N/A|N/A|N/A|N/A|120 I have tried What's the best way to remove duplicates from a string in PHP (or any language)?, detecting duplicate string in a explode function php and like this How to detect duplicate values in PHP array? one too. But none of these works in my case. Coz my data is not unique for same User say Marja_Roxburgh. I wants to remove all entries of Marja_Roxburgh based on its email but also wants to keep the first one only and sum all amounts from its transactions. I've been googling for any logic Im not able to understand what to do this it. How Do I keep only first Record of Marja_Roxburgh and remove all other of her. And also sum all her Amounts before removing her data? I'm missing the logic to understand and solve this problem. Can somebody help me understand this logic? any Ideas? Thanks
  11. Hi, I have a little snipplet I am posting here, I am not very experienced with PHP but thought I would ask some of you for help. I have to modify a program and a very small part of it is to remove lines where values are being set to blank or '' null values. Here is the little code snipplet: echo "\t\tfor(index=0; index < $maxclothrows; index++)\n"; echo "\t\t{\n"; echo "\t\t\tdocument.pickDivision.cloth.options[index].text = '';\n"; echo "\t\t\tdocument.pickDivision.cloth.options[index].value = '';\n"; echo "\t\t}\n\n"; This above code is used to set some values to ' ', but then after I would like those blank values removed rather then showing up in the list because when I scroll down you have a whole bunch of blank lines. How can I remove these completely? Maybe: echo "\t\t\if(document.pickDivision.cloth.options[index].text = '') {...some code here to remove this blank line} I read about regex or some str_replace, but am not sure how to use it. This program is around 3000 lines of code, so don't think I can attach the file. Any help would be greatly appreciated!
  12. how to validate european phone number? i will got mad plz help me to sort this one
  13. Hi, I am still learning PHP and given some HTML I am trying to extract all links and iframes from the HTML and append them to a different string. I am still learning PHP so I am not sure if how I am checking that the returned array has values (isset) or if I should be appending strings together (.) is correct The code that I have so far is function GetLinksIFrames($content) { $innerContent =''; $regex_pattern_links = "/<a href=\"(.*)\">(.*)<\/a>/"; preg_match_all($regex_pattern_links,$content,$matches); for ($i = 0; $i < count($matches); $i++) { if(isset($matches[0][$i]))// Is this correct? { $innerContent = $innerContent.$matches[0][$i]." "; // Is this how to append a result to an existing string? } } $regex_pattern_iframe = "/<iframe src=\"(.*)\">(.*)<\/iframe>/"; preg_match_all($regex_pattern_iframe,$content,$matches); for ($i = 0; $i < count($matches); $i++) { if(isset($matches[0][$i])) { $innerContent = $innerContent.$matches[0][$i]." "; } } return $innerContent; } Any help appreciated Thanks Mark
  14. Hi, I'm trying to turn input from textarea into an array here is what the textarea input look like [input 1] [input 2] [input 3] I'm trying to split everything inside the square bracket "[]" into an array. here are my codes $option = array(); $regex = "#[\[^]]*#s"; $input = "[input 1] [input 2] [input 3]"; $option = preg_split($regex, $input, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE ); the output is Array ( [0] => input 1] [1] => input 2] [2] => input 3] ) the closing bracket still there, So what am I missing in the regex pattern? Thanks
  15. I'm trying to create a field that will validation US phone numbers, and afterwards I will be attempting a field to validate income. So far, for the phone numbers, I have implemented the following regex expression and PHP. The regex has worked in someone elses implementation, however when I utilize it in this implementation it always returns an error that the phone number isn't valid. I'm having a difficult time seeing where the difficulty is: //1. Add a new form element... add_action('register_form','myplugin_register_form2'); function myplugin_register_form2 (){ $phone_number = ( isset( $_POST['phone_number'] ) ) ? $_POST['phone_number']: ''; ?> <p id="phone_number"> <label for="phone_number"><?php _e('Phone Number <font size="1">(XXX XXX XXXX)</font>','mydomain') ?><br /> <input type="text" name="phone_number" id="phone_number" class="input" size="25" style="text-align:right" maxlength="14" /> </p> <?php } //2. Add validation. In this case, we make sure phone_number is required. add_filter('registration_errors', 'myplugin_registration_errors2', 10, 3); function myplugin_registration_errors2 ($errors, $sanitized_user_login, $user_email) { $sPattern = "/^ (?: # Area Code (?: \( # Open Parentheses (?=\d{3}\)) # Lookahead. Only if we have 3 digits and a closing parentheses )? (\d{3}) # 3 Digit area code (?: (?<=\(\d{3}) # Closing Parentheses. Lookbehind. \) # Only if we have an open parentheses and 3 digits )? [\s.\/-]? # Optional Space Delimeter )? (\d{3}) # 3 Digits [\s\.\/-]? # Optional Space Delimeter (\d{4})\s? # 4 Digits and an Optional following Space (?: # Extension (?: # Lets look for some variation of 'extension' (?: (?:e|x|ex|ext)\.? # First, abbreviations, with an optional following period | extension # Now just the whole word ) \s? # Optionsal Following Space ) (?=\d+) # This is the Lookahead. Only accept that previous section IF it's followed by some digits. (\d+) # Now grab the actual digits (the lookahead doesn't grab them) )? # The Extension is Optional $/x"; // /x modifier allows the expanded and commented regex $aNumbers = array( '123-456-7890x123', '123.456.7890x123', '123 456 7890 x123', '(123) 456-7890 x123', '123.456.7890x.123', '123.456.7890 ext. 123', '123.456.7890 extension 123456', '123 456 7890', '123-456-7890ex123', '123.456.7890 ex123', '123 456 7890 ext123', '456-7890', '456 7890', '456 7890 x123', '1234567890', '() 456 7890' ); foreach($aNumbers as $sNumber) { if (!preg_match($sPattern, $phone_number, $aMatches)) { $errors->add( 'phone_number_error', __('<strong>ERROR</strong>: You must include a valid phone number.','mydomain') ); return $errors; } } if ( empty( $_POST['phone_number'] ) ) $errors->add( 'phone_number_error', __('<strong>ERROR</strong>: You must include a valid phone number.','mydomain') ); return $errors; } //3. Finally, save our extra registration user meta. add_action('user_register', 'myplugin_user_register2'); function myplugin_user_register2 ($user_id) { if ( isset( $_POST['phone_number'] ) ) update_user_meta($user_id, 'phone_number', $_POST['phone_number']); }
  16. Hey guys, i have already created a log-in / register system for my website, and i am currently trying to integrate a web forum from phpBB3. i have installed the forum correctly and it is up and running just fine. what i am having an issue with is merging the register systems of both and matching the queries of each databases username and password.and am somewhat lost in watching a tutorial. i have my login logic: <?include('include/init.php'); // DB CONNECTION AND SESSION START .. etc // Redirects user if already logged in logged_in_redirect(); if (empty($_POST) === false) { $username = $_POST['loginname']; $password = $_POST['loginpass']; if (empty($username) === true || empty($password) === true) { $errors[] = 'You need to enter a valid Username & Password'; } else if (user_exists($username) === false ) { $errors[] = ' We could not find this user info in our userbase.'; } else if (user_active($username) === false ) { $errors[] = 'This account still needs to be activated or is no longer active'; } else { $login = login($username, $password); if ($login === false) { $errors[] = ' The Username / Password combination you entered is incorrect.'; } else { $_SESSION['user_id'] = $login; header("Location: index.php"); exit(); } } }else { $errors[] = 'No Data Retrieved'; } if (empty($errors) === false) { ?> <div style=" width: auto; height: 300px; margin: auto; padding: none; text-align: center; position: relative; top: 300px;"> <h5> We tried our best to log you in, but.. <? echo output_errors($errors); }?> Click <a href="redirect.php">Here</a> to go back to the login. </h5> </div> and my sessions logic in the INIT.php: ob_start(); if(!isset($_SESSION)) { session_start(); } error_reporting(E_ALL| E_STRICT); ini_set('display_errors', 1); require_once ('core/database/dbconnect.php'); require_once ('core/functions/general.php'); require_once ('core/functions/users.php'); require_once 'core/queries/dbqueries.php'; require_once ('forums/phpBB3/includes/functions.php'); $current_file = explode('/', $_SERVER['SCRIPT_NAME']); $current_file = end($current_file); if (logged_in() === true) { $session_user_id = $_SESSION['user_id']; $user_data = user_data($session_user_id, 'user_id', 'username', 'password', 'email', 'gender', 'country', 'month' ,'date' , 'year', 'pass_recover', 'type'); if (user_active($user_data['username']) === false){ session_destroy(); header('Location: index.php'); exit(); } if($current_file !== 'change_password.php' && $current_file !== 'logout.php' && $user_data['pass_recover'] == 1 ){ header('Location: change_password.php?force'); exit(); } } $errors = array(); ?> now i have uploaded my phpbb3 file and set them into a directory called forums and in this directory come a bunch of predefined functions. so i wanted to start to add the conditionals to check to see if it was finding the other forums register info i added this: } else { $login = login($username, $password); if ($login === false) { $errors[] = ' The Username / Password combination you entered is incorrect.'; } else {$find = mysql_query("SELECT * FROM phpbb_users WHERE username = '$username' "); ----| if(mysql_num_rows($find)==0) { | echo "ERROR"; | } else { | while ($find_row = mysql_fetch_assoc($find)){ | // THIS WHOLE SNIPPET HAS BEEN ADDED $password_hash = $find_row['user_password']; | } | echo $password_hash; | } ----| $_SESSION['user_id'] = $login; header("Location: index.php"); exit(); } } i had to go into the main functions of the and comment out this line of code so my page would show /*if (!defined('IN_PHPBB')) { exit; } */ nothing seems to output when i add these conditionals, and i at this point i am just lost as to how to get this task done. i can still login with a user who registered using the site / but typing in the username of a user who has registered via forum is not outputting anything. any suggestion or ideas ? i really would appreciate any help on this
  17. Alright, I've had a some nightmares with it already so i bow my stupid head to the almighty hive-mind. I run a small DB with the codes for spare parts. The codes are alphanumerical and i need some proper way to search for them. They can include special chars like parentheses (), and/or @, #, &, $, <, >. So the codes could look like: "A", "Bb", "2C8", "A7(BO)19", "B29H$", "29H(6JI)0#", "29H(6JI)0#<O>", etc The problem is that all these special chars in codes are optional. And the user should be able to find the code by at least its alphabetical part. So the query is something like: SELECT * FROM table WHERE column REGEXP '^[a-z0-9\@\#\$\&\<>()]* AND column LIKE CONCAT('%', '$user_value', '%') The DB doesnt return me "S(LJ)9" or "09S(LJ)3$" if i seek for "SLJ" or "S(LJ)" Would appreciate any help.
  18. Hi, I wonder whether someone may be able to help me please. I'm using the regex expression below as part of my form validation. else if(!preg_match('/^[A-Za-z0-9 .,;-]{5,60}$/', $locationname)) As it currently stands the expression works fine, but I'm having great difficulty when tyrying to add the ' (apostrophe). I've been working on this for a couple of days now, escaping the charcater, moving it to different positions within the expression, sadly without any luck. I just wondered whether someone could possibly look at this please and let me know where I'm going wrong and put me out of my misery . Many thanks and kind regards Chris
  19. Hey everyone! It's been a while ^^ So I've run into a regex problem, it was never my strong point tbh, however, I've come across an issue I can't seem to find a solution to Basically I'm using the following regex to check if a password meets the requirements, which are: Contains a letter Contains a number Can use only A to Z, a to z, 0 to 9 and any of these in the password too:!@#$%. What's going on? Heres line 81, and the error I'm getting. elseif(preg_match('^(?=.*\d+)(?=.*[A-z])[0-9A-z!@#$%]$', $pwds['pwd'])!=1) $problems['pwd']='Passwords must contain one letter and number. Also allowed: .!@#$%'; A PHP Error was encountered Severity: Warning Message: preg_match(): No ending delimiter '^' found Filename: controllers/daemon.php Line Number: 81 Thanks! Gergy.
  20. Okay - I'm trying to split the following string while perserving the values I used to split the string. I've tried searching on this and can't seem to figure out how to accomplish what I'm after using examples I've found. Here's what I have so far: var string = '[{"require":true,"minLengthInput":"6"},{"require":true,"emailAddress":"email"}]'; console.log(string.split(/},{(?=},{/)); So I want to perserve the },{ in the objects that come back. The above doesn't work at all but the output I want is: var[0] = [{"require":true,"minLengthInput":"6"}, var[1] = {"require":true,"emailAddress":"email"}] Thanks for any help you can provide me.
  21. so i am creating a bbcode parser, and i am having a little issue with my pattern. #\[([b|i|u])]((?:[^[]|\[(?!/?\1])|(?R))+)\[/\1]#i this works for b,i & u tags; however i am trying to implement a tag that is longer then 1 character (not sure why this would cause a problem, but it does) and add a parameter. i have tried the pattern below, but without luck. #\[([b|i|u|color])(?:=(.+))]((?:[^[]|\[(?!/?\1])|(?R))+)\[/\1]#i if someone could point me in the right direction, that would be amazing..
  22. At present I have wrote the code below to parse Twitter hashtags "#emotionalclothing". What I really want to do is parse hashtags or status updates with any instance of the phase "emotionalclothing". So say there's a word that reads "blahemotionalclothingblah" in a status update how could retrieve that status update just by searching for a regex with "emotionalclothing" in it? Here's my code so far: Thanks Stuart <?php $pagetitle = "Pull Twitter Hashtags"; function getTweets($hash_tag) { $url = 'http://search.twitter.com/search.atom?q='.urlencode($hash_tag) ; echo "<p>Connecting to <strong>$url</strong> ...</p>"; $ch = curl_init($url); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE); $xml = curl_exec ($ch); curl_close ($ch); //If you want to see the response from Twitter, uncomment this next part out: //echo "<p>Response:</p>"; //echo "<pre>".htmlspecialchars($xml)."</pre>"; $affected = 0; $twelement = new SimpleXMLElement($xml); foreach ($twelement->entry as $entry) { $text = trim($entry->title); $author = trim($entry->author->name); $time = strtotime($entry->published); $id = $entry->id; echo "<p>Tweet from ".$author.": <strong>".$text."</strong> <em>Posted ".date('n/j/y g:i a',$time)."</em></p>"; } return true ; } getTweets('#emotionalclothing'); ?>
  23. Hello I am new to this forum, so I am not sure if I have done this write by starting a new topic, if I was not supposed to start a new topic apologies in advance. Basically I want to get a price from a website and update my database with that value in the correct field. So far I have managed to get the price and update the database. However the price is stored as boolean format so when I output the variable it says "0" or "1" and when the database is updated it says "0" or "1". Here is my working code so far. I have tried using intval, doubleval and data type castings but obviously they equal the boolean value. $url = 'a website goes here'; $html = file_get_contents($url); $search = '/<span class="price">(.*?)<\/span>/'; preg_match_all($search, $html, $matches); $price = array_shift($matches[0]); $price1 = str_replace("£","",$price); $price2 = str_replace(',','', $price1); $price3 = str_replace(".","",$price2); print_r($price3); MySQL query is okay as it is. It would be great if you could help me with this code, thanks in advance.
  24. Hi there, I am working with a web api that has specific requirements for the way it's passwords are formatted. I have used regex very rarely and therefore am very unfamiliar with how to structure them. Basically one of the requirements is that the password entered should: Be - not-repeating such as 'aaaa' AND Be - not-incremental such as '1234' or 'abcd' My current code looks like this: // Password requirements: // Length: Minimal 4 chars, maximum 39 chars if (strlen($password) >= 4 && strlen($password) < 40) { // the password has at least 4 chars and is less than 40 chars in length // Move on... } else { array_push($errors,'Your <strong>Password</strong> must be between <strong>4 and 39</strong> characters in length. Please try again.'); } // Allowed chars: a-z, A-Z, 0-9, minus, underscore, at-sign and dot REGEX TO GO HERE? // Additional: not-repeating and not-incremental like 'aaaa' or '1234' or 'abcd' REGEX TO GO HERE? Could someone help me with the formatting please. I did look at the various links on first post in the forum but it was still way over my head!!!? Any help would be much appreciated.
  25. Hello i was having trouble creating an array with regex. I have an excel sheet with various time formats including: 1h 51m 10.5s, 51m, 10m 10.5s, 5s and I need to convert the time down to minutes. Currently my regex is as follows and does not work: /(([0-9]{1,2})h)?(([0-9]{1,2})m)?(([0-9]{1,2}\.[0-9]{0,2})s)?/ Cold any one help a noob out, Im trying to separate each segment in to an array's cell so i can manipulate it later. My code for the entire function is as follows: public function convertToMinutes($subject) { //Regular Expression to remove text $pattern = '/(([0-9]{1,2})h)?(([0-9]{1,2})m)?(([0-9]{1,2}\.[0-9]{0,2})s)?/'; $numbers = preg_split($pattern, $subject); if (empty($numbers)) { $this -> _flash('warning'); $return['errors'][] = __(sprintf('Regular Expression is wrong'), true); } else { //There are only hours, minutes and seconds if (count($numbers) == 3) { $totalMinutes = 0; $hourMinutes = $numbers[0]; $minutes = $numbers[1]; $secondMinutes = $numbers[2]; $totalMinutes = $hourMinutes / 60; $totalMinutes = $totalMinutes + ($secondMinutes * 60); $totalMinutes = $totalMinutes + ($minutes); return $totalMinutes; debug(count($numbers)); } // There is only minutes and seconds elseif (count($numbers) == 2) { $totalMinutes = 0; $minutes = $numbers[0]; $secondMinutes = $numbers[1]; $totalMinutes = $totalMinutes + ($secondMinutes * 60); $totalMinutes = $totalMinutes + ($minutes); return $totalMinutes;debug(count($numbers)); } else { //Return the minutes return $numbers[0]; } } }
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.