strings and regular expressions adapted from: mac newbold slides

23
Strings and Regular Expressions Adapted from: Mac Newbold slides

Upload: marjory-freeman

Post on 17-Jan-2016

224 views

Category:

Documents


0 download

TRANSCRIPT

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

Strings and Regular Expressions

Adapted from: Mac Newbold slides

Page 2: Strings and Regular Expressions Adapted from: Mac Newbold slides

2

Outline

Intro to Strings in PHPFunctions relating to HTML, SQL, etc.Performance/Speed considerationsGrab bag of cool string functionsRegular Expressions

PCREPOSIX

Page 3: Strings and Regular Expressions Adapted from: Mac Newbold slides

3

Must-Have String Functions

www.php.net/stringsecho/print

چاپ رشته در خروجیtrim, ltrim, rtrim/chop

)حذف فواصل سفید ) یا کاراکترهای دلخواه $trimmed = rtrim($text, " \t.");

explode, implode/join $arr = explode(“ “, “List of words”); $str = implode(“,”,$arr);

جدا کننده

Page 4: Strings and Regular Expressions Adapted from: Mac Newbold slides

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 بار اول با هر دو پارامتر و دفعات بعدی

فقط با پارامتر دوم صدا زده می شود.

Page 5: Strings and Regular Expressions Adapted from: Mac Newbold slides

5

Basic String Manipulation

str_replace(“bar”,”baz”,”foobar”); str_repeat(“1234567890”,8); strtolower, strtoupper ucfirst, ucwords

اولین کاراکتر جمله، یا اولین کاراکتر هر کلمه را به بزرگ تبدیلکن.

str_pad(“tooshort”,15,” ”);

تابعstr_pad دارای آرگومان چهارمی هم نیز هست که جهت را مشخص می کند. padاضافه کردن

سایز نهایی

پد

Page 6: Strings and Regular Expressions Adapted from: Mac Newbold slides

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.

Page 7: Strings and Regular Expressions Adapted from: Mac Newbold slides

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 )

Page 8: Strings and Regular Expressions Adapted from: Mac Newbold slides

8

Formatting functions

date(), strftime()تبدیل زمان به رشته

strtotime(), strptime()تبدیل رشته به زمان

Page 9: Strings and Regular Expressions Adapted from: Mac Newbold slides

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 .استفاده می شود

Page 10: Strings and Regular Expressions Adapted from: Mac Newbold slides

10

HTML Functions

htmlspecialchars را با < و &, “, >, کاراکترهای& amp;, &quot;, &lt ,;

جایگزین می کند.;gt &وhtmlentities .کاراکترهای بیشتری را جایگزین می کندhtml_entity_decode معکوسhtmlentities.است

nl2br \(n) را با برچسب < br >.عوض می کند

parse_str یکquery از نوع GET )را به متغییر )از نوع آرایه

تجزیه می کند.

Page 11: Strings and Regular Expressions Adapted from: Mac Newbold slides

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>

Page 12: Strings and Regular Expressions Adapted from: Mac Newbold slides

12

Grab Bag

md5, md5_file با استفاده ازmd5 رشته یا فایل داده شده را رمز می

کند. .برای ذخیره رمز عبور در پایگاه داده مفید است

levenshtein, similar_text .درجه مشابهت نوشتاری دو رشته را محاسبه می کند

metaphone, soundex .درجه مشابهت گفتاری دو رشته را محاسبه می کند

str_rot13 یک الگوریتم رمز نگاری

Page 13: Strings and Regular Expressions Adapted from: Mac Newbold slides

13

Grab Bag 2

str_shuffle .کاراکترهای کلمه را به هم می ریزد

count_chars, str_word_count آماری مفید در مورد رشته

str_rev معکوس کردن یک رشته

قاعده سر انگشتی: از ساده ترین تابعی که کار راانجام می دهد استفاده کنید.

ازstrpos به جای substr.استفاده کنید ازstr_replace به جای preg_replace.استفاده کنید

Page 14: Strings and Regular Expressions Adapted from: Mac Newbold slides

14

Regular Expressions

عبارات منظم یک ابزار بسیار قوی برای تطابق الگواست.

کامپایلرها و مفسرها نیز در اجرای برنامه از اینتکنیک استفاده می کنند.

درPHP:دو پیاده سازی از عبارات منظم وجود دارد PCRE – Perl-Compatible Regular Expressions POSIX Extended

PCRE زبانهای زیادی از این روش استفاده می کنند وbinary-safe

است. همچنین سریعتر و دارای قابلیتهای بیشتری است.

Page 15: Strings and Regular Expressions Adapted from: Mac Newbold slides

15

Basics of RE’s

RE ها با الگوها مطابقت می کنند. قسمت جالب با آن مطابقت کند.REالگویی است که می خواهید

الگو باید دقیق باشد. یعنی هر آنچه که می خواهیدو هر آنچه که نمی خواهید را دقیقا مشخص نمایید.

اشخاص معموال با احتیاط ازRE استفاده می کنند چون جزییات می توانند مخاطره آمیز باشند.

اما به هر حالRE ها یکی از بهترین ابزارهایی هستند که می شود از آنها برای انجام کارهای

اعجاب برانگیز استفاده نمود.

Page 16: Strings and Regular Expressions Adapted from: Mac Newbold slides

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 # ftp at the beginning of a linee$ # e at the end of a linetle$ # tle at the end of a lineund* # un followed by zero or more d characters. This will match un, 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.

Page 17: Strings and Regular Expressions Adapted from: Mac Newbold slides

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

برای گروه بندی اشیاء )...( برای ”یا“ی منطقی و از |از استفاده کنید.

Page 18: Strings and Regular Expressions Adapted from: Mac Newbold slides

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

Page 19: Strings and Regular Expressions Adapted from: Mac Newbold slides

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

Page 20: Strings and Regular Expressions Adapted from: Mac Newbold slides

20

Greediness and Modifiers

!عبارات منظم حریص هستند.آنها تا جایی که می توانند عمل تطبیق را ادامه می دهند را هنگام “>]^<[*<” را با “>.*<” مثال: رفتار

مقایسه کنید.<”b>Hi</b“>مطابقت با نسخهPCRE دارای بهبود دهنده (modifier) نیز

هست: /<pattern>/<mods> /i = case insensitive /U = un-greedy /m = multi-line

Page 21: Strings and Regular Expressions Adapted from: Mac Newbold slides

21

Back References

پرانتز عالوه بر گروه بندی دارای خاصیت ذخیره مقدار داخل پرانتز نیز هست.

و یک شماره به مقدار \می توان با استفاده از ذخیره شده دسترسی داشت.

مثال“ab(.)\1(.)\2” با abccdd یا abxxyy مطابقت مطابقت ندارد. abdcdc یا abcccdدارد اما با

وقتی که از پرانتزهای تودرتو استفاده می کنیم ؛تشخیص اینکه هر شماره به کدام پرانتز اشاره

دارد دشوار می شود.

Page 22: Strings and Regular Expressions Adapted from: Mac Newbold slides

22

PCRE Specifics

www.php.net/pcrepreg_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);

Page 23: Strings and Regular Expressions Adapted from: Mac Newbold slides

23

POSIX Specifics

www.php.net/regexereg, 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.