search
HomeBackend DevelopmentPHP TutorialPHP learning series (1) - string processing function (4), php function_PHP tutorial

PHP学习系列(1)——字符串处理函数(4),php函数

16、hebrevc() 函数把希伯来文本从右至左的流转换为左至右的流。它也会把新行 (\n) 转换为
。只有 224 至 251 之间的 ASCII 字符,以及标点符号受到影响。

语法:hebrev(string,maxcharline)
maxcharline规定每行的最大字符数。如果可能,hebrev() 将避免把单词断开。

提示:hebrev() 和 hebrevc() 可以把希伯来逻辑文本转换为希伯来可见文本。希伯来可见文本不需要特殊的右至左字符支持,这使它对于在 web 上显示希伯来文本很有用处。

17、htmlspecialchars() 函数把一些预定义的字符转换为 HTML 实体。

预定义的字符是:

  • & (和号) 成为 &
  • " (双引号) 成为 "
  • ' (单引号) 成为 '
语法:htmlspecialchars(string,quotestyle,character-set)

quotestyle——可选。规定如何编码单引号和双引号。

  • ENT_COMPAT - 默认。仅编码双引号。
  • ENT_QUOTES - 编码双引号和单引号。
  • ENT_NOQUOTES - 不编码任何引号。

character-set——可选。字符串值,规定要使用的字符集。

  • ISO-8859-1 - 默认。西欧。
  • ISO-8859-15 - 西欧(增加 Euro 符号以及法语、芬兰语字母)。
  • UTF-8 - ASCII 兼容多字节 8 比特 Unicode
  • cp866 - DOS 专用 Cyrillic 字符集
  • cp1251 - Windows 专用 Cyrillic 字符集
  • cp1252 - Windows 专用西欧字符集
  • KOI8-R - 俄语
  • GB2312 - 简体中文,国家标准字符集
  • BIG5 - 繁体中文
  • BIG5-HKSCS - Big5 香港扩展
  • Shift_JIS - 日语
  • EUC-JP - 日语

提示:无法被识别的字符集将被忽略,并由 ISO-8859-1 代替。

例子

<span><</span><span>html</span><span>></span>
<span><</span><span>body</span><span>></span>
<span><?</span><span>php
$str = "John & 'Adams'";
echo htmlspecialchars($str, ENT_COMPAT);
echo "<br />";
echo htmlspecialchars($str, ENT_QUOTES);
echo "<br />";
echo htmlspecialchars($str, ENT_NOQUOTES);
</span><span>?></span>
<span></</span><span>body</span><span>></span>
<span></</span><span>html</span><span>></span>

浏览器输出:

John & 'Adams'
John & 'Adams'
John & 'Adams'

如果在浏览器中查看源代码,会看到这些 HTML:

<span><</span><span>html</span><span>></span>
<span><</span><span>body</span><span>></span><span>
John </span><span>&</span> 'Adams'<span><</span><span>br </span><span>/></span><span>
John </span><span>&</span> &#039;Adams&#039;<span><</span><span>br </span><span>/></span><span>
John </span><span>&</span><span> 'Adams'
</span><span></</span><span>body</span><span>></span>
<span></</span><span>html</span><span>></span>

 

18、htmlspecialchars_decode() 函数把一些预定义的 HTML 实体转换为字符,是htmlspecialchars() 的反函数。

语法:htmlspecialchars_decode(string,quotestyle)

quotestyle的具体含义同htmlspecialchars()。

19、implode() 函数把数组元素组合为一个字符串。

语法:implode(separator,array)
separator——可选。规定数组元素之间放置的内容。默认是 ""(空字符串)。

array——必需。要结合为字符串的数组。

说明:虽然 separator 参数是可选的。但是为了向后兼容,推荐您使用使用两个参数。

注释:implode() 可以接收两种参数顺序。但是由于历史原因,explode() 是不行的。你必须保证 separator 参数在 string 参数之前才行。

例子

<?<span>php
</span><span>$arr</span> = <span>array</span>('Hello','World!','Beautiful','Day!'<span>);
</span><span>echo</span> <span>implode</span>(" ",<span>$arr</span><span>);
</span>?>

输出:

Hello World! Beautiful Day!
20、join() 函数把数组元素组合为一个字符串。join() 函数是 implode() 函数的别名。
21、levenshtein() 函数返回两个字符串之间的 Levenshtein 距离。

Levenshtein 距离,又称编辑距离,指的是两个字符串之间,由一个转换成另一个所需的最少编辑操作次数。许可的编辑操作包括将一个字符替换成另一个字符,插入一个字符,删除一个字符。

例如把 kitten 转换为 sitting:

levenshtein() 函数给每个操作(替换、插入和删除)相同的权重。不过,您可以通过设置可选的 insert、replace、delete 参数,来定义每个操作的代价。

语法:levenshtein(string1,string2,insert,replace,delete)
参数 描述
string1 必需。要对比的第一个字符串。
string2 必需。要对比的第二个字符串。
insert 可选。插入一个字符的代价。默认是 1。
replace 可选。替换一个字符的代价。默认是 1。
delete 可选。删除一个字符的代价。默认是 1。

注意:

如果其中一个字符串超过 255 个字符,levenshtein() 函数返回 -1。levenshtein() 函数对大小写不敏感。levenshtein() 函数比 similar_text() 函数更快。不过,similar_text() 函数提供需要更少修改的更精确的结果。

例子

<?<span>php
</span><span>echo</span> <span>levenshtein</span>("Hello World","ello World"<span>);
</span><span>echo</span> "<br />"<span>;
</span><span>echo</span> <span>levenshtein</span>("Hello World","ello World",10,20,30<span>);
</span>?>

输出:

1
30
22、localeconv() 函数返回包含本地数字及货币信息格式的数组。
23、ltrim() 函数从字符串左侧删除空格或其他预定义字符。功能类似于chop()或者rtrim();
24、md5() 函数计算字符串的 MD5 散列。md5() 函数使用 RSA 数据安全,包括 MD5 报文摘译算法。如果成功,则返回所计算的 MD5 散列,如果失败,则返回 false。

语法:md5(string,raw)

raw——可选。规定十六进制或二进制输出格式:

  • TRUE - 原始 16 字符二进制格式
  • FALSE - 默认。32 字符十六进制数

注释:该参数是 PHP 5.0 中添加的。

25、md5_file() 函数计算文件的 MD5 散列。md5() 函数使用 RSA 数据安全,包括 MD5 报文摘译算法。如果成功,则返回所计算的 MD5 散列,如果失败,则返回 false。

例子 1
<?<span>php
</span><span>$filename</span> = "test.txt"<span>;
</span><span>$md5file</span> = <span>md5_file</span>(<span>$filename</span><span>);
</span><span>echo</span> <span>$md5file</span><span>;
</span>?>

输出:

5d41402abc4b2a76b9719d911017c592
26、metaphone() 函数计算字符串的 metaphone 键。metaphone 键字符串的英语发音。metaphone() 函数可用于拼写检查应用程序。
如果成功,则返回字符串的 metaphone 键,如果失败,则返回 false。

语法:metaphone(string,length)

length——可选。规定 metaphone 键的最大长度。

说明:metaphone() 为发音相似的单词创建相同的键。所生成的 metaphone 键长度可变。metaphone() 比 soundex() 函数更精确,因为 metaphone() 了解基本的英语发音规则。

例子:

例子 1
<?<span>php
</span><span>echo</span> <span>metaphone</span>("world"<span>);
</span>?>

输出:

WRLT

例子 2

在本例中,我们对两个发音相似的单词应用 metaphone() 函数:

<?<span>php
</span><span>$str</span> = "Sun"<span>;
</span><span>$str2</span> = "Son"<span>;

</span><span>echo</span> <span>metaphone</span>(<span>$str</span><span>);
</span><span>echo</span> <span>metaphone</span>(<span>$str2</span><span>);
</span>?>

输出:

SN
SN
27、money_format() 函数把字符串格式化为货币字符串。

语法:money_format(string,number)
number——可选。被插入格式化字符串中 % 符号位置的数字。

注释:money_format() 函数无法在 windows 平台上工作。

例子:

例子 1

国际 en_US 格式:

<?<span>php
</span><span>$number</span> = 1234.56<span>;
</span><span>setlocale</span>(LC_MONETARY, "en_US"<span>);
</span><span>echo</span> money_format("The price is %i", <span>$number</span><span>);
</span>?>

输出:

The price is USD 1,234.56

例子 2

负数,带有 () 指示负数的 US 国际格式,右侧精度为 2,"*" 为填充字符:

<?<span>php
</span><span>$number</span> = -1234.5672<span>;

</span><span>echo</span> money_format("%=*(#10.2n", <span>$number</span><span>);
</span>?>

输出:

($********1,234.57)
28、nl_langinfo() 函数返回指定的本地信息。

如果成功,则返回指定的本地信息。如果失败,则返回 false。

语法:nl_langinfo(element)

element——必需。规定要返回哪个元素。必须是说明中列出的元素之一。

说明:

时间和日历:

  • ABDAY_(1-7) - Abbreviated name of the numbered day of the week
  • DAY_(1-7) - Name of the numbered day of the week (DAY_1 = Sunday)
  • ABMON_(1-12) - Abbreviated name of the numbered month of the year
  • MON_(1-12) - Name of the numbered month of the year
  • AM_STR - String for Ante meridian
  • PM_STR - String for Post meridian
  • D_T_FMT - String that can be used as the format string for strftime() to represent time and date
  • D_FMT - String that can be used as the format string for strftime() to represent date
  • T_FMT - String that can be used as the format string for strftime() to represent time
  • T_FMT_AMPM - String that can be used as the format string for strftime() to represent time in 12-hour format with ante/post meridian
  • ERA - Alternate era
  • ERA_YEAR - Year in alternate era format
  • ERA_D_T_FMT - Date and time in alternate era format (string can be used in strftime())
  • ERA_D_FMT - Date in alternate era format (string can be used in strftime())
  • ERA_T_FMT - Time in alternate era format (string can be used in strftime())

货币类别:

  • INT_CURR_SYMBOL - Currency symbol (example: USD)
  • CURRENCY_SYMBOL - Currency symbol (example: $)
  • CRNCYSTR - Same as CURRENCY_SYMBOL
  • MON_DECIMAL_POINT - Monetary decimal point character
  • MON_THOUSANDS_SEP - Monetary thousands separator
  • POSITIVE_SIGN - Positive value character
  • NEGATIVE_SIGN -Negative value character
  • MON_GROUPING - Array displaying how monetary numbers are grouped (example: 1 000 000)
  • INT_FRAC_DIGITS - International fractional digits
  • FRAC_DIGITS - Local fractional digits
  • P_CS_PRECEDES - True (1) if currency symbol is placed in front of a positive value, False (0) if it is placed behind
  • P_SEP_BY_SPACE - True (1) if there is a spaces between the currency symbol and a positive value, False (0) otherwise
  • N_CS_PRECEDES - True (1) if currency symbol is placed in front of a negative value, False (0) if it is placed behind
  • N_SEP_BY_SPACE - True (1) if there is a spaces between the currency symbol and a negative value, False (0) otherwise
  • P_SIGN_POSN - Formatting setting. Possible return values:
    • 0 - Parentheses surround the quantity and currency symbol
    • 1 - The sign string is placed in front of the quantity and currency symbol
    • 2 - The sign string is placed after the quantity and currency symbol
    • 3 - The sign string is placed immediately in front of the currency symbol
    • 4 - The sign string is placed immediately after the currency symbol
  • N_SIGN_POSN - Formatting setting. Possible return values:
    • 0 - Parentheses surround the quantity and currency symbol
    • 1 - The sign string is placed in front of the quantity and currency symbol
    • 2 - The sign string is placed after the quantity and currency symbol
    • 3 - The sign string is placed immediately in front of the currency symbol
    • 4 - The sign string is placed immediately after the currency symbol

数字类别:

  • DECIMAL_POINT - Decimal point character
  • RADIXCHAR - Same as DECIMAL_POINT
  • THOUSANDS_SEP - Separator character for thousands
  • THOUSEP - Same as THOUSANDS_SEP
  • GROUPING - Array displaying how numbers are grouped (example: 1 000 000)

通信类别:

  • YESEXPR - Regex string for matching 'yes' input
  • NOEXPR - Regex string for matching 'no' input
  • YESSTR - Output string for 'yes'
  • NOSTR - Output string for 'no'

代码集类别:

  • CODESET Return a string with the name of the character encoding.

提示和注释

注释:money_format() 函数无法在 windows 平台上工作。

提示:与返回所有本地格式化信息的 localeconv() 函数不同,nl_langinfo() 返回指定的信息。

29、nl2br() 函数在字符串中的每个新行 (n) 之前插入 HTML 换行符 (
)。

语法:nl2br(string)
<?<span>php
</span><span>echo</span> <span>nl2br</span>("One line.\nAnother line."<span>);
</span>?>

输出:

One line.
Another line.

HTML 代码:

One line.<span><</span><span>br </span><span>/></span><span>
Another line.</span>
30、number_format() 函数通过千位分组来格式化数字。

语法:number_format(number,decimals,decimalpoint,separator)

number——必需。要格式化的数字。如果未设置其他参数,则数字会被格式化为不带小数点且以逗号 (,) 作为分隔符。

decimals——可选。规定多少个小数。如果设置了该参数,则使用点号 (.) 作为小数点来格式化数字。

decimalpoint——可选。规定用作小数点的字符串。

separator——可选。规定用作千位分隔符的字符串。仅使用该参数的第一个字符。比如 "xyz" 仅输出 "x"。注释:如果设置了该参数,那么所有其他参数都是必需的。

注释:该函数支持一个、两个或四个参数(不是三个)。

例子

<span><?</span><span>php
echo number_format("1000000");
echo number_format("1000000",2);
echo number_format("1000000",2,",",".");
</span><span>?></span>

输出:

1,000,000
1,000,000.00
1.000.000,00
 

php 怎处理字符串

大家通过对PHP的学习,可以运用这一高级语言创建一个性能较高的网站。对于初学者来说,对于PHP字符串mbstring还是比较陌生的,下面我们就来介绍一下PHP字符串mbstring的具体应用。

多国语言并存就意味着多字节,PHP内置的字符串长度函数strlen无法正确处理中文字符串,它得到的只是字符串所占的字节数。对于GB2312的中文编码,strlen得到的值是汉字个数的2倍,而对于UTF-8编码的中文,就是1~3倍的差异了。

采用PHP字符串mbstring可以较好地解决这个问题。mb_strlen的用法和strlen类似,只不过它有第二个可选参数用于指定字符编码。例如得到UTF-8的字符串$str长度,可以用mb_strlen($str,’UTF-8′)。如果省略第二个参数,则会使用PHP的内部编码。内部编码可以通过mb_internal_encoding()函数得到,设置有两种方式:

1. 在php.ini中设置mbstring.internal_encoding = UTF-8

2. 调用mb_internal_encoding(”GBK”)

除了PHP字符串mbstring,还有很多切割函数,其中mb_substr是按字来切分字符,而mb_strcut是按字节来切分字符,但是都不会产生半个字符的现象。而且从函数切割对长度的作用也不同,mb_strcut的切割条件是小于strlen, mb_substr是等于strlen,看下面的例子,



输出如下:

mb_substr:我是一串比较

mb_strcut:我是

需要注意的是,PHP字符串mbstring并不是PHP核心函数,使用前需要确保在php编译模块时加入mbstring的支持:

(1)编译时使用–enable-mbstring

(2)修改/usr/local/lib/php.inc

default_charset = “zh-cn”

mbstring.language = zh-cn

mbstring.internal_encoding =zh-cn

PHP字符串mbstring类库内容比较多,还包括mb_ send_ mail 之类的email处理函数等
 

(100分)[php]写几个你熟悉的字符串处理函数!

addcslashes addslashes bin2hex chop chr chunk_split convert_cyr_string cyrillic
convert_uudecode convert_uuencode count_chars crc32 crc32 crypt echo explode

fprintf get_html_translation_table hebrev

hebrevc
hex2bin — Decodes a hexadecimally encoded binary string
html_entity_decode — Convert all HTML entities to their applicable characters
htmlentities — Convert all applicable characters to HTML entities
htmlspecialchars_decode — Convert special HTML entities back to characters
htmlspecialchars — Convert special characters to HTML entities
implode — Join array elements with a string
join

lcfirst — Make a string's first character lowercase
levenshtein — Calculate Levenshtein distance between two strings
localeconv — Get numeric formatting information
ltrim — Strip whitespace (or other characters) from the beginning of a string
md5_file
metaphone — Calculate the metaphone key of a string
money_format — Formats a number as a currency string
nl_langinfo — Query language and locale information
nl2br

number_format — Format a number with grouped thousands
ord

parse_str

print

printf

quoted_printable_decode — Convert a quoted-printable string to an 8 bit string
quoted_printable_encode — Convert a 8 bit string to a quoted-printable string
quotemeta — Quote meta characters
rtrim
setlocale — Set locale information
sha1_file

sha1

soundex — Calculate the soundex key of a string
sprintf — Return a formatted string
sscanf — Parses input from a string according to a ......余下全文>>
 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/891600.htmlTechArticlePHP学习系列(1)字符串处理函数(4),php函数 16、hebrevc() 函数把希伯来文本从右至左的流转换为左至右的流。它也会把新行 (n) 转换为...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How can you prevent session fixation attacks?How can you prevent session fixation attacks?Apr 28, 2025 am 12:25 AM

Effective methods to prevent session fixed attacks include: 1. Regenerate the session ID after the user logs in; 2. Use a secure session ID generation algorithm; 3. Implement the session timeout mechanism; 4. Encrypt session data using HTTPS. These measures can ensure that the application is indestructible when facing session fixed attacks.

How do you implement sessionless authentication?How do you implement sessionless authentication?Apr 28, 2025 am 12:24 AM

Implementing session-free authentication can be achieved by using JSONWebTokens (JWT), a token-based authentication system where all necessary information is stored in the token without server-side session storage. 1) Use JWT to generate and verify tokens, 2) Ensure that HTTPS is used to prevent tokens from being intercepted, 3) Securely store tokens on the client side, 4) Verify tokens on the server side to prevent tampering, 5) Implement token revocation mechanisms, such as using short-term access tokens and long-term refresh tokens.

What are some common security risks associated with PHP sessions?What are some common security risks associated with PHP sessions?Apr 28, 2025 am 12:24 AM

The security risks of PHP sessions mainly include session hijacking, session fixation, session prediction and session poisoning. 1. Session hijacking can be prevented by using HTTPS and protecting cookies. 2. Session fixation can be avoided by regenerating the session ID before the user logs in. 3. Session prediction needs to ensure the randomness and unpredictability of session IDs. 4. Session poisoning can be prevented by verifying and filtering session data.

How do you destroy a PHP session?How do you destroy a PHP session?Apr 28, 2025 am 12:16 AM

To destroy a PHP session, you need to start the session first, then clear the data and destroy the session file. 1. Use session_start() to start the session. 2. Use session_unset() to clear the session data. 3. Finally, use session_destroy() to destroy the session file to ensure data security and resource release.

How can you change the default session save path in PHP?How can you change the default session save path in PHP?Apr 28, 2025 am 12:12 AM

How to change the default session saving path of PHP? It can be achieved through the following steps: use session_save_path('/var/www/sessions');session_start(); in PHP scripts to set the session saving path. Set session.save_path="/var/www/sessions" in the php.ini file to change the session saving path globally. Use Memcached or Redis to store session data, such as ini_set('session.save_handler','memcached'); ini_set(

How do you modify data stored in a PHP session?How do you modify data stored in a PHP session?Apr 27, 2025 am 12:23 AM

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Give an example of storing an array in a PHP session.Give an example of storing an array in a PHP session.Apr 27, 2025 am 12:20 AM

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

How does garbage collection work for PHP sessions?How does garbage collection work for PHP sessions?Apr 27, 2025 am 12:19 AM

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor