php字符串处理函数

tech2023-12-06  34

php字符串处理函数

PHP has a vast selection of built-in string handling functions that allow you to easily manipulate strings in almost any possible way. However, learning all these functions, remembering what they do, and when they might come in handy can be a bit daunting, especially for new developers. There is no way I can cover every string function in one article, and besides, that is what the PHP manual is for! But what I will do is show how to work with some of the most commonly used string handling functions that you should know. After this, you’ll be working with strings as well as any concert violinist!

PHP有大量的内置字符串处理功能供您选择,这些功能使您几乎可以任何方式轻松地操作字符串。 但是,学习所有这些功能,记住它们的功能以及何时使用它们可能会有些艰巨,特别是对于新开发人员而言。 我无法在一篇文章中介绍每个字符串函数,此外,这就是PHP手册的目的! 但是我要做的是展示如何使用一些您应该知道的最常用的字符串处理功能。 之后,您将与弦乐以及任何音乐会小提琴家一起工作!

在案件 (On the Case)

PHP offers several functions that enable you to manipulate the case of characters within a string without having to edit the string character by character. Why would you care about this? Well maybe you want to ensure that certain text is all in upper case such as acronyms, titles, for emphasis or just to ensure names are capitalized correctly. Or maybe you just want to compare two strings and you want to ensure the letters you are comparing are the same character set. The case manipulation functions are pretty easy to get to grips with; you just pass the string as a parameter to the function and the return value you is the processed string.

PHP提供了多种功能,使您能够处理字符串中字符的大小写,而不必逐个字符地编辑字符串。 你为什么要关心这个? 好吧,也许您想确保某些文本全部使用大写字母,例如首字母缩写词,标题,以便强调,或者只是确保名称正确使用大写字母。 或者,也许您只想比较两个字符串,并且要确保比较的字母是相同的字符集。 案例处理功能非常容易掌握。 您只需将字符串作为参数传递给函数,返回值就是已处理的字符串。

If you wanted to ensure all the letters in a specific string were uppercase, you can use the strtoupper() function as follows:

如果要确保特定字符串中的所有字母均为大写字母,可以使用strtoupper()函数,如下所示:

<?php $str = "Like a puppet on a string."; $cased = strtoupper($str); // Displays: LIKE A PUPPET ON A STRING. echo $cased;

It is perhaps obvious but still worth noting that numbers and other non-alphabet characters will not be converted.

也许很明显,但仍然值得注意的是数字和其他非字母字符不会被转换。

As you can probably guess, the strtolower() function does the exact opposite of strtoupper() and converts a string into all lowercase letters:

您可能会猜到, strtolower()函数执行与strtoupper()完全相反的strtoupper() ,并将字符串转换为所有小写字母:

<?php $str = "LIKE A PUPPET ON A STRING."; $cased = strtolower($str); // Displays: like a puppet on a string. echo $cased;

There may be other times when you want to ensure certain words, such as names or titles, just have the first letter of each word capitalized. For this you can use the ucwords() function:

有时您可能想要确保某些单词(例如名称或标题)仅将每个单词的首字母大写。 为此,您可以使用ucwords()函数:

<?php $str = "a knot"; $cased = ucwords($str); // Displays: A Knot echo $cased;

It is also possible to manipulate the case of just the first letter of a string using the lcfirst() and ucfirst() functions. If you want the first letter to be lowercase, use lcfirst(). If you want the first letter to be uppercase, use ucfirst(). The ucfirst() function is probably the most useful since you can use it to ensure a sentence always starts with a capital letter.

也可以使用lcfirst()和ucfirst()函数仅处理字符串的第一个字母的情况。 如果希望首字母小写,请使用lcfirst() 。 如果希望首字母大写,请使用ucfirst() 。 ucfirst()函数可能是最有用的,因为您可以使用它来确保句子始终以大写字母开头。

<?php $str = "how long is a piece of string?"; $cased = ucfirst($str); //Displays: How long is a piece of string? echo $cased;

快速修剪 (A Quick Trim)

Sometimes a string needs trimming round the edges. It may have whitespace or other characters at the beginning or end which needs removing. The whitespace can be an actual space character, but it can also be a tab, carriage return, etc. One example of when you might need to do something like this is when you’re working with user input and you want to clean it up it before you start processing it. The trim() function in PHP lets you to do just that; you can pass the string as a parameter and all whitespace from the beginning and end of that string will be removed:

有时,字符串需要修剪边缘。 它的开头或结尾可能包含空格或其他字符,需要删除。 空格可以是实际的空格字符,但也可以是制表符,回车符等。当您需要使用用户输入并要清理它时,可能需要执行以下操作的一个示例在开始处理它之前。 PHP中的trim()函数使您可以做到这一点; 您可以将字符串作为参数传递,并将删除该字符串开头和结尾的所有空格:

<?php $str = " A piece of string? "; // Displays: string(22) " A piece of string? " var_dump($str); $trimmed = trim($str); // Displays: string(18) "A piece of string?" var_dump($trimmed);

trim() is also multi-purpose in that in addition to the string you can also pass it a set of characters and it will remove any that match from the beginning or end:

trim()也是多功能的,除了字符串之外,您还可以向其传递一组字符,它将从开头或结尾删除所有匹配的字符:

<?php $str = "A piece of string?"; $trimmed = trim($str, "A?"); // Displays: string(16) " piece of string" var_dump($trimmed);

You do need to be careful when you work with these additional characters since trim() will only remove whitespace if you specifically provide it as one of the characters you want removed:

在使用这些其他字符时,您确实需要小心,因为trim()仅在您专门将空白提供为要删除的字符之一时才会删除空格:

<?php $str = "A piece of string?"; $trimmed = trim($str, "A ?"); // Displays: string(15) "piece of string" var_dump($trimmed);

Even though trim() only removes characters at the start and end of a string, it has removed both “A” and the space because when “A” is removed the space becomes the new start of the string, and so that is also removed.

即使trim()仅删除字符串开头和结尾的字符,它也删除了“ A”和空格,因为当删除“ A”时,空格将成为字符串的新开头,因此也将删除。

There are also ltrim() and rtrim() functions in PHP which are similar to the trim() function but only remove whitespace (or other specified characters) from the left or right of the string respectively.

PHP中还有ltrim()和rtrim()函数,它们与trim()函数类似,但分别仅从字符串的左侧或右侧除去空格(或其他指定的字符)。

一段绳子有多长? (How Long is a (Piece of) String?)

Very often when working with strings, you’ll want to know how long it is. For example, when dealing with a form, you may have a field where you want to make sure users can’t go over a certain number of characters. To count the number of characters in a string, you can use the strlen() function:

很多时候使用字符串时,您会想知道它有多长时间。 例如,在处理表单时,您可能需要在一个字段中确保用户不能超过一定数量的字符。 要计算字符串中的字符数,可以使用strlen()函数:

<?php $str = "How long is a piece of string?"; $size = strlen($str); // Displays: 30 echo $size;

将字符串切成小尺寸 (Cutting Strings Down to Size)

Another common situation is finding specific text within a given string and “cutting it” out so you can do something else with it. To cut a string down to size, you need a good pair of scissors, and in PHP your scissors are the substr() function.

另一个常见的情况是在给定的字符串中查找特定的文本并将其“剪切”,以便您可以对它进行其他操作。 为了将字符串切成小尺寸,您需要一把剪刀,而在PHP中,剪刀是substr()函数。

To use the substr() function, pass the string you want to work with as a parameter along with a positive or negative integer. The number determines where you’ll start cutting the string; 0 starts you off at the first character of the string (remember that when you count through a string, the first character on the left starts at position 0, not 1).

要使用substr()函数,请将要使用的字符串作为参数以及正整数或负整数传递。 数字决定了您将在哪里开始切割弦。 0使您从字符串的第一个字符开始(请记住,当您对字符串进行计数时,左侧的第一个字符将从位置0而不是1开始)。

<?php $str = "How to cut a string down to size"; $snip = substr($str, 13); //Displays: string down to size echo $snip;

When you use a negative number, substr() will start backwards from the end of the string.

当您使用负数时, substr()将从字符串的末尾开始。

<?php $str = "How to cut a string down to size"; $snip = substr($str, -7); //Displays: to size echo $snip;

An optional third parameter to substr() is the length, another integer value that allows you to specify the number of characters you want to extract from the string.

substr()第三个可选参数是length,另一个整数值使您可以指定要从字符串中提取的字符数。

<?php $str = "How to cut a string down to size"; $snip = substr($str, 13, 6); //Displays: string echo $snip;

If you just need to find the position of a particular piece of text within a string and nothing else, you can use the strpos() function which returns the position your selection is from the start of the string. A useful trick, especially when you don’t know the starting position of the text you to cut from a string, is to combine the two functions. Rather than specifying a start position as an integer, you can search for a specific piece of text and then extract that.

如果只需要查找字符串中特定文本的位置,而没有别的,则可以使用strpos()函数,该函数从字符串的开头返回您选择的位置。 一个有用的技巧是将两个功能结合在一起,尤其是当您不知道要从字符串中剪切的文本的起始位置时。 您可以搜索特定文本,然后提取该文本,而不是将起始位置指定为整数。

<?php $str = "How to cut a string down to size"; $snip = substr($str, strpos($str, "string"), 6); //Displays: string echo $snip;

交换商店 (Swap Shop)

Finally, let’s look at replacing a piece of the string with something else, for which you can use str_replace() function. This is ideal for situations where you just want to swap out instances of specific words or a set of characters in a string and replace them with something else:

最后,让我们看一下用其他替换字符串的部分,您可以使用str_replace()函数。 对于只想交换特定单词或字符串中的一组字符的实例并用其他替换它们的情况而言,这是理想的选择:

<?php $oldstr = "The cat was black"; $newstr = str_replace("black", "white", $oldstr); // Displays: The cat was white echo $newstr;

You can also provide arrays to str_replace() if you want to replace multiple values:

如果要替换多个值,还可以向str_replace()提供数组:

<?php $oldstr = "The flag was red white and blue."; $america = array("red", "white", "blue"); $germany = array("black", "red", "yellow"); $newstr = str_replace($america, $germany, $oldstr); // Displays: The flag was black red and yellow. echo $newstr;

str_replace() is case-sensitive, so if you don’t want to worry about that then you can use its case-insensitive sibling instead, str_ireplace().

str_replace()区分大小写,因此,如果您不想担心该问题,可以使用不区分大小写的同级str_ireplace() 。

摘要 (Summary)

Hopefully, this article has given you a taste of some of the things you can do with strings in PHP and made you hungry to learn more. I’ve really barely scraped the tip of the iceberg! The best place to find out more about all of the different string functions is to take some time to read the String Functions page in the PHP Manual.

希望本文使您对使用PHP中的字符串可以做的事情有所了解,并渴望了解更多。 我真的几乎没有刮过冰山一角! 了解所有所有不同字符串函数的最佳地方是花一些时间阅读PHP手册中的“字符串函数”页面。

I’d love to know which string functions you find yourself using most often, so feel free to mention them in the comments below.

我想知道您最常使用哪种字符串函数,因此请在下面的评论中随意提及它们。

Image via Vasilius / Shutterstock

图片来自Vasilius / Shutterstock

翻译自: https://www.sitepoint.com/string-handling-functions/

php字符串处理函数

最新回复(0)