PHP Strings. Outline o String Variables In PHP o The Most Used Functions In PHP o Arrays Functions o Transforming String o Comparing Strings o Searching.

Slides:



Advertisements
Similar presentations
Chapter 6 Lists and Dictionaries CSC1310 Fall 2009.
Advertisements

Strings.
Lecture 9. Lecture 9: Outline Strings [Kochan, chap. 10] –Character Arrays/ Character Strings –Initializing Character Strings. The null string. –Escape.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Current Assignments Homework 5 will be available tomorrow and is due on Sunday. Arrays and Pointers Project 2 due tonight by midnight. Exam 2 on Monday.
CS31: Introduction to Computer Science I Discussion 1A 5/7/2010 Sungwon Yang
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
To remind us We finished the last day by introducing If statements Their structure was:::::::::
C. About the Crash Course Cover sufficient C for simple programs: variables and statements control functions arrays and strings pointers Slides and captured.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
CS Nov 2006 C-strings.
Validating user input Basharat Mahmood, Department of Computer Science,CIIT,Islamabad, Pakistan. 1.
Operations & Strings CSCI 116 Web Programming I. 2 Arithmetic Operators Arithmetic operators are used to perform mathematical calculations.
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
PHP Overview CS PHP PHP = PHP: Hypertext Preprocessor Server-side scripting language that may be embedded into HTML One goal is to get PHP files.
Strings and Arrays. String Is a sequence of characters. Example: “hello”, “how are you?”, “123”,and are all valid string values.
Strings IDIA 618 Spring 2013 Bridget M. Blodgett.
Input/Output Chapters 7 & 9. Output n Print produces output > (print 100) n It also returns the value it printed –that’s where the second 100 came.
Outline o What is String ? o Basic String o Using String As Arrays o Transforming String o Comparing Strings o Searching Strings o Matching Against Mask.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 9 More About Strings.
PHP Controlling Program Flow Mohammed M. Hassoun 2012.
Mr. Justin “JET” Turner CSCI 3000 – Fall 2015 CRN Section A – TR 9:30-10:45 CRN – Section B – TR 5:30-6:45.
Characters The data type char represents a single character in Java. –Character values are written as a symbol: ‘a’, ‘)’, ‘%’, ‘A’, etc. –A char value.
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition1  Wiley and the.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
CH2 – Using Data. Constant Something which cannot be changed Data Type Format and size of a data item Intrinsic Data Types Pg. 47 – Table 2-1 Basic ones.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
Strings in PHP Working with Text in PHP Strings and String Functions Mario Peshev Technical Trainer Software University
Introduction to PHP – Part 2 Sudeshna Dey. Arrays A series of homogeneous elements Elements have values in form of stored data Has a key associated with.
Web Database Programming Week 3 PHP (2). Functions Group related statements together to serve “a” specific purpose –Avoid duplicated code –Easy maintenance.
1Computer Sciences Department Princess Nourah bint Abdulrahman University.
ITM © Port, KazmanVariables - 1 ITM 352 Data types, Variables.
Data TypestMyn1 Data Types The type of a variable is not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which.
1 PHP Intro PHP Strings After this lecture, you should be able to: Manipulate and Output PHP Strings: Manipulate and Output PHP Strings: Single- or Double-quoted.
Operations on Strings. 8/8/2005 Copyright 2006, by the authors of these slides, and Ateneo de Manila University. All rights reserved L: String Manipulation.
Arrays II (Strings). Data types in C Integer : int i; Double: double x; Float: float y; Character: char ch; char cha[10], chb[]={‘h’,’e’,’l’,’l’,’o’};
Copyright © 2002, Department of Systems and Computer Engineering, Carleton University CONTROL STRUCTURES Simple If: if (boolean exp) { statements.
String String Builder. System.String string is the alias for System.String A string is an object of class string in the System namespace representing.
Strings Mr. Smith AP Computer Science A. What are Strings? Name some of the characteristics of strings: A string is a sequence of characters, such as.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 21 Thanks for Lecture Slides:
Coding Bat: Ends in ly Given a string of even length, return a string made of the middle two chars, so the string "string" yields "ri". The string.
C++ String Class nalhareqi©2012. string u The string is any sequence of characters u To use strings, you need to include the header u The string is one.
Copyright © 2002, Department of Systems and Computer Engineering, Carleton University 1 INPUT STREAMS ifstream xin; // declares an input stream.
Strings Programming Applications. Strings in C C stores a string in a block of memory. The string is terminated by the \0 character:
1 Chapter 3 – Handling Strings and Arrays spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology.
 2003 Prentice Hall, Inc. All rights reserved. 5.11Function Pointers Pointers to functions –Contain address of function –Similar to how array name is.
2.1 Scalar data - revision numeric e-14 ( = 6.35 × )‏ operators: + (addition) - (subtraction) * (multiplication) / (division)
UniMAP SEM I - 09/10EKT 120 Computer Programming1 Lecture 8 – Arrays (2) & Strings.
 Variables can store data of different types, and different data types can do different things.  PHP supports the following data types:  String  Integer.
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
Slide 1 PHP Predefined Functions ITWA113. Murach’s ASP.NET 3.5/C#, C1© 2008, Mike Murach & Associates, Inc. Slide 2 PHP Predefined Functions Objectives.
DCT1063 Programming 2 CHAPTER 3 STRINGS Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
Strings, and the string Class. C-Strings C-string: sequence of characters stored in adjacent memory locations and terminated by NULL character The C-string.
1 Arrays and Pointers The name of an array is a pointer constant to the first element. Because the array’s name is a pointer constant, its value cannot.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 this week – last section on Friday. Assignment 4 is posted. Data mining: –Designing functions.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
String and Lists Dr. José M. Reyes Álamo.
ITM 352 Data types, Variables
Arrays in C.
PHP.
String and Lists Dr. José M. Reyes Álamo.
String functions
Web Programming Language
Topics Basic String Operations String Slicing
Python Strings.
Topics Basic String Operations String Slicing
String functions
Topics Basic String Operations String Slicing
Presentation transcript:

PHP Strings

Outline o String Variables In PHP o The Most Used Functions In PHP o Arrays Functions o Transforming String o Comparing Strings o Searching Strings o String Replace

String Variables in PHP String objects are a special type of container, specifically designed to operate with sequences of characters. A string variable is used to store and manipulate text. String variables are used for values that contain characters.

String Variables in PHP String can be defined using one of several methods, we encapsulate them in single quotes or double quotes. We using the string to display some notation.

 The Most Used Functions In PHP

Strlen() Returns the length of the given string. The length of the string on success, and 0 if the string is empty. Int strlen(string)

Strlen() <?php $str = "welcome in my profile"; echo strlen($str); ?>

strtoupper() Returns string with all alphabetic characters converted to uppercase. Returns the uppercased string. string strtoupper ( string $string )

strtoupper() <?php $str = “make a string uppercase "; $str = strtoupper($str); echo $str; ?>

strtolower () Returns string with all alphabetic characters converted to lowercase. Returns the lowercased string. string strtolower ( string $string )

strtolower() <?php $str = “MAKE A STRING LOWERCASE "; $str = strtolower($str); echo $str; ?>

ucfirst() Returns a string with the first character of str capitalized, if that character is alphabetic. Returns the resulting string. string ucfirst ( string $str )

ucfirst() <?php $str = “Make a string's first character uppercase "; $str = ucfirst($str); echo $str; ?>

ucwords() Returns a string with the first character of each word in str capitalized, if that character is alphabetic. Returns the modified string. string ucwords ( string $str )

ucwords() <?php $str = “uppercase the first character of each word in a string "; $str = ucwords($str); echo $str; ?>

substr_count() substr_count() returns the number of times the needle substring occurs in the haystack string. Please note that needle is case sensitive. This function returns an integer. int substr_count ( string $haystack, string $needle [, int $offset = 0 [, int $length ]] )

substr_count()

explode () Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter. <?php // Example 1 $chars = “A B C D E F"; $pieces = explode(" ", $chars); echo $pieces[0]; // A echo $pieces[1]; // B ?> array explode ( string $delimiter, string $string [, int $limit ] )

implode () Join array elements with a glue string. Returns a string containing a string representation of all the array elements in the same order, with the glue string between each element. string implode ( string $glue, array $pieces ) string implode ( array $pieces )

implode () <?php $array = array('lastname', ' ', 'phone'); $comma_separated = implode(",", $array); echo $comma_separated; // lastname, ,phone ?>

str_split () Converts a string to an array. If the optional split_length parameter is specified, the returned array will be broken down into chunks with each being split_length in length, otherwise each chunk will be one character in length. FALSE is returned if split_length is less than 1. If the split_length length exceeds the length of string, the entire string is returned as the first (and only) array element. array str_split ( string $string [, int $split_length = 1 ] )

str_split ()

str_repeat () Returns input repeated multiplier times. <?php echo str_repeat("-=", 10); ?> string str_repeat ( string $input, int $multiplier )

strrev() Returns string, reversed. Returns the reversed string. string strrev ( string $string )

strrev() <?php echo strrev("Hello world!"); // outputs "!dlrow olle ?>

str_word_count() Specify the return value of this function. The current supported values are: 0 - returns the number of words found 1 - returns an array containing all the words found inside the string 2 - returns an associative array, where the key is the numeric position of the word inside the string and the value is the actual word itself str_word_count ( string $string [, int $format = 0 [, string $charlist ]] )

str_word_count()

str_shuffle () str_shuffle() shuffles a string. One permutation of all possible is created. Returns the shuffled string. string str_shuffle ( string $str )

str_shuffle () <?php $str = 'abcdef'; $shuffled = str_shuffle($str); // This will echo something like: bfdaec echo $shuffled; ?> string str_shuffle ( string $str )

rand () If called without the optional min, max arguments rand() returns a pseudo- random integer between 0 and getrandmax(). If you want a random number between 5 and 15 (inclusive), for example, use rand(5, 15) int rand ( void ) int rand ( int $min, int $max )

rand () <?php echo rand(). "\n"; echo rand(). "\n"; echo rand(5, 15); ?>

round () Returns the rounded value of val to specified precision (number of digits after the decimal point). precision can also be negative or zero (default). The rounded value round ( float $val [, int $precision = 0 [, int $mode = PHP_ROUND_HALF_UP ]] )

round () <?php echo round(3.4); // 3 echo round(3.5); // 4 echo round(3.6); // 4 echo round(3.6, 0); // 4 echo round( , 2); // 1.96 echo round( , -3); // echo round(5.045, 2); // 5.05 echo round(5.055, 2); // 5.06 ?>

round () <?php echo round(9.5, 0, PHP_ROUND_HALF_UP); // 10 echo round(9.5, 0, PHP_ROUND_HALF_DOWN); // 9 echo round(9.5, 0, PHP_ROUND_HALF_EVEN); // 10 echo round(9.5, 0, PHP_ROUND_HALF_ODD); // 9 echo round(8.5, 0, PHP_ROUND_HALF_UP); // 9 echo round(8.5, 0, PHP_ROUND_HALF_DOWN); // 8 echo round(8.5, 0, PHP_ROUND_HALF_EVEN); // 8 echo round(8.5, 0, PHP_ROUND_HALF_ODD); // 9 ?>

max() If the first and only parameter is an array, max() returns the highest value in that array. If at least two parameters are provided, max()returns the biggest of these values. max ( array $values ) max ( $value1, $value2 [, $value3... ] )

max() max() returns the numerically highest of the parameter values. If multiple values can be considered of the same size, the one that is listed first will be returned. When max() is given multiple arrays, the longest array is returned. If all the arrays have the same length, max() will use lexicographic ordering to find the return value. When given a string it will be cast as an integer when comparing.

max()

min() If the first and only parameter is an array, min() returns the lowest value in that array. If at least two parameters are provided, min() returns the smallest of these values. min() returns the numerically lowest of the parameter values. min ( array $values ) min ( $value1, $value2 [, $... ] )

min() ?php echo min(2, 3, 1, 6, 7); // 1 echo min(array(2, 4, 5)); // 2 echo min(0, 'hello'); // 0 echo min('hello', 0); // hello echo min('hello', -1); // -1 ?>

str_pad () This functions returns the input string padded on the left, the right, or both sides to the specified padding length. If the optional argument pad_string is not supplied, the input is padded with spaces, otherwise it is padded with characters from pad_string up to the limit. Returns the padded string. string str_pad ( string $input, int $pad_length [, string $pad_string = " " [, int $pad_type = STR_PAD_RIGHT ]] )

str_pad () <?php $input = "Alien"; echo str_pad($input, 10); // produces "Alien " echo str_pad($input, 10, "-=", STR_PAD_LEFT); // produces "-=-=-Alien" echo str_pad($input, 10, "_", STR_PAD_BOTH); // produces "__Alien___" echo str_pad($input, 6, "___"); // produces "Alien_“ ?>

wordwrap() Wraps a string to a given number of characters using a string break character. Returns the given string wrapped at the specified length. string wordwrap ( string $str [, int $width = 75 [, string $break = "\n" [, bool $cut = false ]]] )

wordwrap() \n"); echo $newtext; ?>

 Array Functions

Using String As Arrays You can acces the individual characters of a strings as if they were members of an array. Ex1 :$str = “abcdef”; echo $str[‘1’] ; // b Or for($i =0 ;$i < srtlen($str); $i++) { echo $str[$i]; }

array_push() array_push () Push one or more elements onto the end of array Returns the new number of elements in the array. int array_push ( array &$array, $var [, mixed $... ] )

array_push() <?php $stack = array("orange", "banana"); array_push($stack, "apple", "raspberry"); print_r($stack); ?>

array_pop() array_pop — Pop the element off the end of array Returns the last value of array. If array is empty (or is not an array), NULL will be returned. array_pop ( array &$array )

array_pop() <?php $stack = array("orange", "banana", "apple", "raspberry"); $fruit = array_pop($stack); print_r($stack); ?>

array_merge () array_merge — Merge one or more arrays Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array. If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended. Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array. Returns the resulting array. array array_merge ( array $array1 [, array $... ] )

array_merge () "red", 2, 4); $array2 = array("a", "b", "color" => "green", 4); $result = array_merge($array1, $array2); print_r ($array1); print_r ($array2); print_r($result); ?>

array_rand () array_rand — Pick one or more random entries out of an array Picks one or more random entries out of an array, and returns the key (or keys) of the random entries. If you are picking only one entry, array_rand() returns the key for a random entry. Otherwise, it returns an array of keys for the random entries. This is done so that you can pick random keys as well as values out of the array. array_rand ( array $input [, int $num_req = 1 ] )

array_rand () <?php $bmw = array(“X2", “X3", “X4", “X5", “X6"); $rand_keys = array_rand($bmw, 2); echo $bmw[$rand_keys[0]]. "\n"; echo $bmw[$rand_keys[1]]. "\n"; ?

array_replace () array_replace — Replaces elements from passed arrays into the first array array_replace() replaces the values of the first array with the same values from all the following arrays. If a key from the first array exists in the second array, its value will be replaced by the value from the second array. If the key exists in the second array, and not the first, it will be created in the first array. If a key only exists in the first array, it will be left as is. If several arrays are passed for replacement, they will be processed in order, the later arrays overwriting the previous values. array_replace() is not recursive : it will replace values in the first array by whatever type is in the second array. Returns an array, or NULL if an error occurs. array array_replace ( array $array, array $array1 [, array $... ] )

array_replace () "pineapple", 4 => "cherry"); $replacements2 = array(0 => "grape"); $basket = array_replace($base, $replacements, $replacement s2); print_r($basket); ?>

range () range — Create an array containing a range of elements Returns an array of elements from start to limit, inclusive. array range ( mixed $start, mixed $limit [, number $step = 1 ] )

range ()

shuffle () This function shuffles (randomizes the order of the elements in) an array. Returns TRUE on success or FALSE on failure. bool shuffle ( array &$array )

shuffle () <?php $numbers = range(1, 20); shuffle($numbers); foreach ($numbers as $number) { echo "$number "; } ?>

asort () asort — Sort an array and maintain index association This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant. Returns TRUE on success or FALSE on failure. bool asort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

asort () "lemon", "a" => "orange", "b" => "banan a", "c" => "apple"); asort($fruits); foreach ($fruits as $key => $val) { echo "$key = $val\n"; } ?>

usort () usort — Sort an array by values using a user-defined comparison function This function will sort an array by its values using a user- supplied comparison function. If the array you wish to sort needs to be sorted by some non-trivial criteria, you should use this function. Returns TRUE on success or FALSE on failure. bool usort ( array &$array, callable $cmp_function )

usort () $value) { echo "$key: $value\n"; } ?>

ksort () Sorts an array by key, maintaining key to data correlations. This is useful mainly for associative arrays. Returns TRUE on success or FALSE on failure. bool ksort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

ksort () "lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple "); ksort($fruits); foreach ($fruits as $key => $val) { echo "$key = $val\n"; } ?>

array_fill () Fills an array with num entries of the value of the value parameter, keys starting at the start_index parameter. Returns the filled array. array array_fill ( int $start_index, int $num, mixed $value )

array_fill () <?php $a = array_fill(5, 6, 'banana'); $b = array_fill(-2, 4, 'pear'); print_r($a); print_r($b); ?>

empty () Determine whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals FALSE. empty() does not generate a warning if the variable does not exist. bool empty ( $var )

empty () Returns FALSE if var exists and has a non-empty, non-zero value. Otherwise returns TRUE. The following things are considered to be empty: "" (an empty string) 0 (0 as an integer) 0.0 (0 as a float) "0" (0 as a string) NULL FALSE array() (an empty array) $var; (a variable declared, but without a value)

empty () <?php $arr = array(); If(empty($arr)) Echo “empty array”; ?>

 Transforming String

Transforming String If given two arguments, the second should be an array in the form array('from' => 'to',...). The return value is a string where all the occurrences of the array keys have been replaced by the corresponding values. The longest keys will be tried first. Once a substring has been replaced, its new value will not be searched again. string strtr ( string $str, array $replace_pairs )

Transforming String  "Hi", "world" => "earth"); echo strtr("Hello world",$arr); ?>  Output : Hi earth

Transforming String The strtr() If given three arguments, this function returns a copy of str where all occurrences of each (single-byte) character in from have been translated to the corresponding character in to, i.e., every occurrence of $from[$n] has been replaced with $to[$n], where $n is a valid offset in both arguments.; string strtr ( string $str, string $from, string $to )

Transforming String Output : Hello World

 Comparing Strings

Comparing Strings You can comparison between strings by more than one method,the PHP when comparison it make convert the data type to other if the data type not the same. Ex1: <?php If(“123aa” == 123) { echo “done”; } ?>

Comparing Strings This comparison is case sensitive. Returns 0 if str1 is greater than str2, and 0 if they are equal. int strcmp ( string $str1, string $str2 )

Comparing Strings Output : 0

Comparing Strings Binary safe case-insensitive string comparison. Returns 0 if str1 is greater than str2, and 0 if they are equal. int strcasecmp ( string $str1, string $str2 )

Comparing Strings <?php $var1 = "Hello"; $var2 = "hello"; if (strcasecmp($var1, $var2) == 0) { echo '$var1 is equal to $var2 in a case-insensitive string comparison'; } ?>

Comparing Strings-example <?php $str = "Ali"; if(strcmp($str, "ali") == 0) { //we won't get here, becuse of case sensitivity } if(strcasecmp($str, "ali") == 0) { we well get here becuse strcasecmp() is case-insensitive } ?>

Comparing Strings-example <?php $st1 = “abcd1234”; $st2 = “abcd5678”; echo strncasecmp ($st1,$st2,4); ?>

 Searching Strings

Searching Strings Find the numeric position of the first occurrence of needle in the haystack string. Returns the position of where the needle exists relative to the beginning of the haystack string (independent of offset). Also note that string positions start at 0, and not 1. Returns FALSE if the needle was not found. int strpos ( string $haystack, $needle [, int $offset = 0 ] )

Searching Strings Output : 6

Searching Strings-Example <?php $str =“abcdef”; $se_str = “abc”; If(strpos($str,$se_srt) !== false) { echo “found”; } ?>

Searching Strings-Example <?php $str =' '; $se_str = '123'; echo strpos($str,$se_str,1); //false ?>

Searching Strings-Example <?php $str ='123456'; $se_str = ‘34'; echo strtr($str,$se_str,1); // 3456 ?>

String Replace This function returns a string or an array with all occurrences of search in subject replaced with the given replace value. This function returns a string or an array with all occurrences of search in subject (ignoring case) replaced with the given replace value. eplaces a copy of string delimited by the start and (optionally) length parameters with the string given inreplacement. str_replace ( $search, $replace, $subject [, int &$count ] ) str_ireplace ( $search, $replace, $subject [, int &$count ] ) substr_replace ( $string, $replacement, $start [, $length ] )

String Replace-example <?php echo str_raplace(“Mr”,”Welcom”,”Mr Ali”); echo str_iraplace(“Mr”,”Welcom”,”Mr Ali”); ?>

String Replace -exmple <?php $a = 0; echo str_raplace(“a”,”b”,”a1a1a1”,$a); echo $a // 3 ?>

String Replace -exmple <?php echo substr_raplace(“welecom ali ”,”hi”,7); echo substr_raplace(“welecom my brother ali ”,”mr”,9,10); ?>

String Replace -exmple <?php $str = “ ”; echo substr($str,0,3);//123 echo substr($str,1,1);//2 echo substr($str,-2);//89 echo substr($str,-2,1);//8 ?>

str_replace()

str_replace() <?php $arr = array("blue","red","green","yellow"); print_r(str_replace("red","pink",$arr,$i)); echo "Replacements: $i"; ?>

str_replace() <?php $arr = array("blue","red","green","yellow"); print_r(str_replace("red","pink",$arr,$i)); echo "Replacements: $i"; ?>