Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

PHP functions to work with strings

See in this article the main functions of the PHP language to work with strings, performing operations as convert to upper or lower case, get a substring or replicate a string.

This article intends to show and explain how and when use the main functions to manipulate strings in the PHP language. At the end of this text you should be able to perform the main operations with this data type, as convert an expression to upper case or lower case, get a substring, know whether a string is contained within another, replace a part of a string, and others.

The functions that we’ll see are: strtoupper, strtolower, substr, str_pad, str_repeat, strlen, str_replace, and strpos, in this order.

strtoupper

The first function we’ll see, strupper, receives a string as parameter and returns the same value with all characters converted to upper case.

On the Listing 1 we can see this function form and an example of use.

Listing 1: Example of use of the strtoupper function

<?php
	/*string strtoupper (string content)*/
	$name = "joel rodrigues";
	$uppercase_name = strtoupper($name);
	echo $uppercase_name;
?>

The output of this code is “JOEL RODRIGUES”.

strtolower

The strtolower works as the inverse of the previous function. It has the same syntax, but returns the received value with all characters converted to lower case.

Then we have an example of use, where an upper case expression is passed as parameter to the strtolower function.

Listing 2: Example of use of the strtolower function

<?php
	/*string strtolower (string content)*/
	$name = "MR. BOOL";
	$lowercase_name = strtolower($name);
	echo $ lowercase_name;
?>

Echo command will print the value “mr. bool”.

substr

This function returns a part of a string passed as first parameter, basing on a position and a length.

This method can be called by three forms: informing the begin of the part we nedd to get, informing the begin and the length or informing the begin and a negative value. On the last form, the limit of the part that will be returned is counted from the end of the string.

On the next listings we’ll see an example of each form.

Listing 3: Using substr passing the begin of the substring

<?php
	/*string substr(string content, int start [,int length])*/
	$name = "Mr. Bool";
	$part = substr($name, 3);
	echo $part;
?>

This code will print the word “Bool”, because will be return all characters from the position 3 till the end.

Listing 4: Using substr passing the start position and the length

<?php
	/*string substr(string content, int start [,int length])*/
	$name = "Model View Controller";
	$part = substr($name, 0, 5);
	echo $part;
?>

Now the output is “Model”, the first five characters from the position 0 (first position).

Listing 5: Using substr passing the start and a negative length

<?php
/*string substr(string content, int start [,int length])*/
	$name = "Model View Presenter";
	$part = substr($name, 6, -10);
	echo $part;
?>

This code will print the word “View”. The start position was defined as 6 and, from the end of the string, the function counts ten characters “backwards”.

str_pad

This function accept a string as parameter and returns other string with the same contente of the first, but complemented with some characters, to get a specified length.

There are three possible calls to this function: passing just the length of the new string, passing the length and the string used to complete the original expression, and passing the length, the complementary string and type of fill.

This last argument is the type that indicates how the original string will be filled. It have three possible values:

  • STR_PAD_LEFT or 0: fills the original string to the left.
  • STR_PAD_RIGHT or 1: fills the original string to the right.
  • STR_PAD_BOTH: fills the original string to both sides.

The default value, if this parameter is not passed, is STR_PAD_RIGHT.

On the next listings we’ll see some examples of use.

Listing 6: Basic usage of str_pad

<?php
	/*string str_pad(string original, int length [,string complement[, int type]])*/

	$name = "PHP";
	$complete_name = str_pad($name, 5);
	echo $complete_name;
?>

In this code we passed the text “PHP” to the function and defined that the return should have 5 characters, without inform the string that should be used to complete the original. Then, the text “PHP” will be completed with 2 characters (blank spaces) to the right. The return is “PHP “.

Listing 7: Using str_pad passing the complementary string

<?php
	/*string str_pad(string original, int length [,string complement[, int type]])*/
	$name = "PHP";
	$complete_name = str_pad($name, 5, "*");
	echo $complete_name;
?>

In the code above was defined that the string should be filled with a star (*). Now the return will be “PHP**”, again a total of five characters.

Listing 8: Using str_pad defining the fill type

<?php
	/*string str_pad(string original, int length [,string complement[, int type]])*/
	$name = "PHP";
	$left = str_pad($name, 5, "*", STR_PAD_LEFT);
	$right = str_pad($name, 5, "*", STR_PAD_RIGHT);
	$both = str_pad($name, 5, "*", STR_PAD_BOTH);
	echo $left;
	echo "\n";
	echo $right;
	echo "\n";
	echo $both;
?>

The Listing 8 shows the three possible values for the fourth argument. At the end of the execution, the variable $left will have the value “**PHP”, the variable $right will have the value “PHP**” and the variable $both will contain “*PHP*”.

Note 1: instead of the name of the types, we could pass the value of each one (0, 1 or 3).

Note 2: when using the STR_PAD_BOTH type for the type parameter and passing a odd value, the right side will be filled first. For instance, if the length passed was 6, the $both variable would have the value “*PHP**”.

str_repeat

This function is used to “repeat” a string by a defined number of times.It’s syntax is very simple: the first parameter is the text to be replicated and the second parameter is a value indicating the number of repeatings.

Below we’ll see it’s syntax and a example of usage.

Listing 9: Example of use of str_repeat

<?php
	/*string str_repeat (string text, int quantity)*/
	$replicated = str_repeat("0", 5);
	echo $replicated;
?>

After runing the code above, the value “00000” will be printed, because we defined that the text “0” should be replicate 5 times.

Note 3: the second parameter should be a integer number equals or greater than zero.

strlen

Maybe this is the most simple function showed in this article, but it’s is very importante, because it’s usage is common. It returns the length of a string passed as parameter.

Listing 10: Example of use of strlen

<?php
	/*string strlen (string text)*/
	$length = strlen("Mr. Bool");
	echo $length;
?>

The printed value will be “8”, because the text “Mr. Bool” has eight characters.

str_replace

Also very commonly used, the function str_replace serves to replace a part of a text by other value. The arguments that should be passed is, in this order: the text to be replaced, the new text, the text that contains the value to be replaced.

On the example below we have the string “Hello, world.”. We’ll use the function str_replace to replace the word “world” by “reader” and then assign the result to another variable.

Listing 11: Example of use of str_replace

<?php
	/*mixed str_replace (mixed search, mixed replace, mixed text)*/
	$text = "Hello, world.";
	$new_text = str_replace("wolrd", "reader", $text);
	echo $new_text;
?>

The output of the code above will be “Hello, reader.”.

strpos

This last function returns the position of a text within another, IE, it is used to know if a string contains a certain value and, in positive case, in which position.

In the next listing we have the text “Wellcome to Mr. Bool” and need to localize the value “Bool” and print the position in which it appears in the main text.

Listagem 12: Exemplo de uso da função strpos

<?php
	/*int strpos (string text, string searched)*/
	$text = "Wellcome to Mr. Bool";
	$pos = strpos($text, "Bool");
	echo $pos;
?>

The output will be “16”, because the word “Bool” starts at the position sixteen.

Conclusion

At the end of this article, the reader should aready be able to work with the string functions in the PHP language. As we saw, this functions has very simple syntaxes and names, what makes the learning easier.

Thank the reader’s attention. See you next time.



Microsoft MVP, Bachelor in Science And Technology, Editor and Consultant at DevMedia with more than 7 years of experience in software development.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login