forked from bradtraversy/php-crash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
08_string_functions.php
56 lines (41 loc) · 1.23 KB
/
08_string_functions.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<?php
/* ---------- String Functions -------- */
/*
Functions to work with strings
https://www.php.net/manual/en/ref.strings.php
*/
$string = 'Hello World';
// Get the length of a string
echo strlen($string);
// Find the position of the first occurrence of a substring in a string
echo strpos($string, 'o');
// Find the position of the last occurrence of a substring in a string
echo strrpos($string, 'o');
// Reverse a string
echo strrev($string);
// Convert all characters to lowercase
echo strtolower($string);
// Convert all characters to uppercase
echo strtoupper($string);
// Uppercase the first character of each word
echo ucwords($string);
// String replace
echo str_replace('World', 'Everyone', $string);
// Return portion of a string specified by the offset and length
echo substr($string, 0, 5);
echo substr($string, 5);
// Starts with
if (str_starts_with($string, 'Hello')) {
echo 'YES';
}
// Ends with
if (str_ends_with($string, 'ld')) {
echo 'YES';
}
// HTML Entities
$string2 = '<h1>Hello World</h1>';
echo htmlentities($string2);
// Formatted Strings - useful when you have outside data
// Different specifiers for different data types
printf('%s is a %s', 'Brad', 'nice guy');
printf('1 + 1 = %f', 1 + 1); // float