1 / 23

Strings and Regular Expressions

Strings and Regular Expressions. Adapted from: Mac Newbold slides. Outline. Intro to Strings in PHP Functions relating to HTML, SQL, etc. Performance/Speed considerations Grab bag of cool string functions Regular Expressions PCRE POSIX. Must-Have String Functions. www.php.net/strings

gray-gould
Télécharger la présentation

Strings and Regular Expressions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Strings and Regular Expressions Adapted from: Mac Newbold slides

  2. Outline • Intro to Strings in PHP • Functions relating to HTML, SQL, etc. • Performance/Speed considerations • Grab bag of cool string functions • Regular Expressions • PCRE • POSIX

  3. Must-Have String Functions • www.php.net/strings • echo/print • چاپ رشته در خروجی • trim, ltrim, rtrim/chop • حذف فواصل سفید ( یا کاراکترهای دلخواه) • $trimmed = rtrim($text, " \t."); • explode, implode/join • $arr = explode(“ “, “List of words”); • $str = implode(“,”,$arr); جدا کننده

  4. Obligatory C-like Functions • printf, sprintf, sscanf, fprintf • strcmp, strlen, • strpos, • $pos = strpos($mystring, $findme); • Strtok • یک رشته را بر اساس کاراکترهای داده شده به چند رشته کوچکتر (نشانه) تبدیل می کند. • $tok = strtok($string, " \n\t"); • نکات: • درتوابعی مثل strpos خروجی صفر معتبر است و به معنای false نیست. در این حالتها ، برای چک کردن خروجی از “===false” استفاده کنید. • برای هر رشته، تابع strtok بار اول با هر دو پارامتر و دفعات بعدی فقط با پارامتر دوم صدا زده می شود.

  5. Basic String Manipulation • str_replace(“bar”,”baz”,”foobar”); • str_repeat(“1234567890”,8); • strtolower, strtoupper • ucfirst, ucwords • اولین کاراکتر جمله، یا اولین کاراکتر هر کلمه را به بزرگ تبدیل کن. • str_pad(“tooshort”,15,” ”); • تابع str_pad دارای آرگومان چهارمی هم نیز هست که جهت اضافه کردن pad را مشخص می کند. سایز نهایی پد

  6. <?php $text = "The quick brown fox jumped over the lazy dog."; $newtext = wordwrap($text, 20, "<br />\n"); echo $newtext;?> خروجی: The quick brown fox<br /> jumped over the lazy<br /> dog.

  7. Formatting functions • vprintf, vfprintf, vsprintf • خروجی فرمت دار print vsprintf("%04d-%02d-%02d", explode('-', '1988-8-1'));  // 1988-08-01 • number_format • دسته بندی هزار تایی • money_format • فرمت مناسب برای پول string money_format ( string $format , float $number )

  8. Formatting functions • date(), strftime() • تبدیل زمان به رشته • strtotime(), strptime() • تبدیل رشته به زمان

  9. URL Functions • urlencode, urldecode • کاراکترهای غیر نوشتاری را به %[hex] و ‘ ‘ را به ’+’تبدیل می کند. echo '<a href="mycgi?foo=', urlencode($userinput), '">'; • rawurl{en,de}code بجز در مورد ‘+’ در بقیه موارد مثل url{en, de}code عمل می کند. • parse_url • URL داده شده را به host, path و query تبدیل می کند. • http_build_query • یک آرایه را تبدیل به یک query آرایه ای تبدیل می کند. <?php $data = array('foo'=>'bar', 'baz'=>'boom', 'cow'=>'milk');echo http_build_query($data);// foo=bar&baz=boom&cow=milk • base64_{en,de}code • تبدیل base64 که در MIME استفاده می شود.

  10. HTML Functions • htmlspecialchars • کاراکترهای &, “, <, و > را با &amp;, &quot;, &lt;, و &gt; جایگزین می کند. • htmlentities کاراکترهای بیشتری را جایگزین می کند. • html_entity_decode معکوس htmlentities است. • nl2br • (\n) را با برچسب <br> عوض می کند. • parse_str • یک query از نوع GET را به متغییر (از نوع آرایه) تجزیه می کند.

  11. strip_tags • برچسبهای HTML را جدا می کند. <?php$text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';echo strip_tags($text);echo "\n";// Allow <p> and <a>echo strip_tags($text, '<p><a>');?> Test paragraph. Other text <p>Test paragraph.</p> <a href="#fragment">Other text</a>

  12. Grab Bag • md5, md5_file • با استفاده از md5 رشته یا فایل داده شده را رمز می کند. • برای ذخیره رمز عبور در پایگاه داده مفید است. • levenshtein, similar_text • درجه مشابهت نوشتاری دو رشته را محاسبه می کند. • metaphone, soundex • درجه مشابهت گفتاری دو رشته را محاسبه می کند. • str_rot13 • یک الگوریتم رمز نگاری

  13. Grab Bag 2 • str_shuffle • کاراکترهای کلمه را به هم می ریزد. • count_chars, str_word_count • آماری مفید در مورد رشته • str_rev • معکوس کردن یک رشته • قاعده سر انگشتی: از ساده ترین تابعی که کار را انجام می دهد استفاده کنید. • از strpos به جای substr استفاده کنید. • از str_replace به جای preg_replace استفاده کنید.

  14. Regular Expressions • عبارات منظم یک ابزار بسیار قوی برای تطابق الگو است. • کامپایلرها و مفسرها نیز در اجرای برنامه از این تکنیک استفاده می کنند. • در PHP دو پیاده سازی از عبارات منظم وجود دارد: • PCRE – Perl-Compatible Regular Expressions • POSIX Extended • PCRE • زبانهای زیادی از این روش استفاده می کنند و binary-safe است. همچنین سریعتر و دارای قابلیتهای بیشتری است.

  15. Basics of RE’s • RE ها با الگوها مطابقت می کنند. قسمت جالب الگویی است که می خواهید RE با آن مطابقت کند. • الگو باید دقیق باشد. یعنی هر آنچه که می خواهید و هر آنچه که نمی خواهید را دقیقا مشخص نمایید. • اشخاص معمولا با احتیاط از RE استفاده می کنند چون جزییات می توانند مخاطره آمیز باشند. • اما به هر حال RE ها یکی از بهترین ابزارهایی هستند که می شود از آنها برای انجام کارهای اعجاب برانگیز استفاده نمود.

  16. More on REs . # Any single character except a newline ^ # The beginning of the line or string $ # The end of the line or string * # Zero or more of the last character + # One or more of the last character ? # Zero or one of the last character {n} # n times {n,m} # n to m times t.e # t followed by anything followed by e. This will match tre, tle but not te, tale ^f # f at the beginning of a line ^ftp # ftpat the beginning of a line e$ # eat the end of a line tle$ # tleat the end of a line und* # unfollowed by zero or moredcharacters. This will matchun, und, undd, unddd,… .* # Any string without a newline. This is because the. matches anything except # a newline and the *means zero or more of these. ^$ # A line with nothing in it. Remember that the RE should be enclosed in /.../ slashes to be used.

  17. Even more on REs jelly|cream # Either jelly or cream (eg|le)gs # Either eggs or legs (da)+ # Either da or dada or dadada or... [qjk]# Either q or j or k [^qjk]# Neither q nor j nor k [a-z]# Anything from a to z inclusive [^a-z]# No lower case letters [a-zA-Z]# Any letter [a-z]+# Any non-zero sequence of lower case letters • –یعنی بینِ • ^یعنی بدونِ از | برای ”یا“ی منطقی و از (...) برای گروه بندی اشیاء استفاده کنید.

  18. Still More on REs \n # A newline \t # A tab \w # Any alphanumeric (word) character. # The same as [a-zA-Z0-9_] \W # Any non-word character. # The same as [^a-zA-Z0-9_] \d # Any digit. The same as [0-9] \D # Any non-digit. The same as [^0-9] \s # Any whitespace character: space, # tab, newline, etc \S # Any non-whitespace character \b # A word boundary, outside [] only \B # No word boundary \| # Vertical bar \[ # An open square bracket \) # A closing parenthesis \* # An asterisk \^ # A carat symbol \/ # A slash \\ # A backslash

  19. Some Example REs [01] # Either "0" or "1" \/0 # A division by zero: "/0" \/ 0 # A division by zero with a space: "/ 0" \/\s0 # A division by zero with a whitespace: # "/ 0" where the space may be a tab etc. \/ *0 # A division by zero with possibly some # spaces: "/0" or "/ 0" or "/ 0" etc. \/\s*0 # A division by zero with possibly some whitespace. \/\s*0\.0* # As the previous one, but with decimal # point and maybe some 0s after it. Accepts # "/0." and "/0.0" and "/0.00" etc and # "/ 0." and "/ 0.0" and "/ 0.00" etc. (abc)+(def|123)*(.{2})* # At least one abc, maybe some triplets, then an even # number of characters

  20. Greediness and Modifiers • عبارات منظم حریص هستند! • آنها تا جایی که می توانند عمل تطبیق را ادامه می دهند. • مثال: رفتار “<.*>” را با “<[^>]*>” را هنگام مطابقت با “<b>Hi</b>” مقایسه کنید. • نسخه PCRE دارای بهبود دهنده (modifier) نیز هست: • /<pattern>/<mods> • /i = case insensitive • /U = un-greedy • /m = multi-line

  21. Back References • پرانتز علاوه بر گروه بندی دارای خاصیت ذخیره مقدار داخل پرانتز نیز هست. • می توان با استفاده از \ و یک شماره به مقدار ذخیره شده دسترسی داشت. • مثلا “ab(.)\1(.)\2” با abccdd یا abxxyy مطابقت دارد اما با abcccd یا abdcdc مطابقت ندارد. • وقتی که از پرانتزهای تودرتو استفاده می کنیم ؛ تشخیص اینکه هر شماره به کدام پرانتز اشاره دارد دشوار می شود.

  22. PCRE Specifics • www.php.net/pcre • preg_match, preg_match_all, preg_replace, preg_split, preg_grep (filter an array) • Perl RE’s have a delimiter, usually /, but can be anything: • preg_match(“/foo/”,$bar); • preg_match(“%/usr/local/bin/%”,$path);

  23. POSIX Specifics • www.php.net/regex • ereg, ereg_replace, split, eregi, spliti, etc. • [Only] Advantage over PCRE: It doesn’t require the PCRE library to be installed, so it’s always there in any PHP installation • Other regex engines support this specification, though the Perl style seems to be more popular.

More Related