Strings in PHP Working with Text in PHP Strings and String Functions Mario Peshev Technical Trainer Software University

Slides:



Advertisements
Similar presentations
Session 3BBK P1 ModuleApril 2010 : [#] Regular Expressions.
Advertisements

BBK P1 Module2010/11 : [‹#›] Regular Expressions.
Data Manipulation & Regular Expressions CSCI 215.
Chapter 3 Manipulating Strings PHP Programming with MySQL 2nd Edition
Manipulating Strings. 2 Topics Manipulate strings Manipulate strings Parse strings Parse strings Compare strings Compare strings Handle form submissions.
Operations & Strings CSCI 116 Web Programming I. 2 Arithmetic Operators Arithmetic operators are used to perform mathematical calculations.
Manipulating Strings. Name of Book2 Objectives Manipulate strings Parse strings Compare strings Handle form submissions.
Lesson 3 – Regular Expressions Sandeepa Harshanganie Kannangara MBCS | B.Sc. (special) in MIT.
Last Updated March 2006 Slide 1 Regular Expressions.
 Text Manipulation and Data Collection. General Programming Practice Find a string within a text Find a string ‘man’ from a ‘A successful man’
PHP Workshop ‹#› Data Manipulation & Regex. PHP Workshop ‹#› What..? Often in PHP we have to get data from files, or maybe through forms from a user.
 Dimitar Ivanov Introduction to programming with microcontrollers.
AngularJS Services Built-in and Custom Services SoftUni Team Technical Trainers Software University
Methods Writing and using methods, overloads, ref, out SoftUni Team Technical Trainers Software University
Software University Curriculum, Courses, Exams, Jobs SoftUni Team Technical Trainers Software University
Chapter 3 Manipulating Strings PHP Programming with MySQL 2nd Edition
Project Tracking Tools Trello, Asana, Basecamp, GitHub Issue Tracker, TRAC SoftUni Team Technical Trainers Software University
AngularJS Directives Defining Custom Directives SoftUni Team Technical Trainers Software University
Software Testing Lifecycle Exit Criteria Evaluation, Continuous Integration Ivan Yonkov Technical Trainer Software University.
ASP.NET Programming with C# and SQL Server First Edition Chapter 5 Manipulating Strings with C#
NoSQL Databases NoSQL Concepts SoftUni Team Technical Trainers Software University
Conditional Statements Implementing Control-Flow Logic in C# SoftUni Team Technical Trainers Software University
Composer packages Installing and Using Composer, Packagist, Packaging your code Mario Peshev Technical Trainer Software University
Loops Repeating Code Multiple Times SoftUni Team Technical Trainers Software University
Svetlin Nakov Technical Trainer Software University
Build Processes and Continuous Integration Automating Build Processes Software University Technical Trainers SoftUni Team.
Web Database Programming Week 3 PHP (2). Functions Group related statements together to serve “a” specific purpose –Avoid duplicated code –Easy maintenance.
Project Tracking Tools Trello, Asana, Basecamp, GitHub Issue Tracker, TRAC Angel Georgiev Part-time Trainer Software University
What is PHP? PHP stands for PHP: Hypertext Preprocessor PHP is a server-side scripting language, like ASP PHP scripts are executed on the server PHP supports.
Test-Driven Development Learn the "Test First" Approach to Coding SoftUni Team Technical Trainers Software University
Functions Reusable Parts of Code SoftUni Team Technical Trainers Software University
Working with Forms and Regular Expressions Validating a Web Form with JavaScript.
When you read a sentence, your mind breaks it into tokens—individual words and punctuation marks that convey meaning. Compilers also perform tokenization.
Java Collections Basics Arrays, Lists, Strings, Sets, Maps Svetlin Nakov Technical Trainer Software University
Arrays, Lists, Stacks, Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
Controllers and Markup Controllers, $scope, Markup, Directives, Expressions, Binding, Filters, Validation SoftUni Team Technical Trainers Software University.
AMD and RequireJS Splitting JavaScript Code into Dependent Modules Software University Technical Trainers SoftUni Team.
Using SQL Connecting, Retrieving Data, Executing SQL Commands, … Svetlin Nakov Technical Trainer Software University
Asynchronous Web Services Writing Asynchronous Web Services SoftUni Team Technical Trainers Software University
Jekyll Static Site Generator Template-Based Site Generation Svetlin Nakov Technical Trainer Software University
Forms Overview, Query string, Submitting arrays, PHP & HTML, Input types, Redirecting the user Mario Peshev Technical Trainer Software.
Working with Forms in PHP HTTP GET / POST, Validation, Escaping, Input Types, Submitting Arrays, URL Redirecting, PHP Superglobals Svetlin Nakov Technical.
Tables, Rows, Columns, Cells, Header, Footer, Colspan, Rowspan
Regular Expressions /^Hel{2}o\s*World\n$/ SoftUni Team Technical Trainers Software University
Design Patterns: Structural Design Patterns General and reusable solutions to common problems in software design Software University
Regular Expressions /^Hel{2}o\s*World\n$/ SoftUni Team Technical Trainers Software University
Operators and Expressions
Mocking Unit Testing Methods with External Dependencies SoftUni Team Technical Trainers Software University
Mocking with Moq Mocking tools for easier unit testing Svetlin Nakov Technical Trainer Software University
Test-Driven Development Learn the "Test First" Approach to Coding Svetlin Nakov Technical Trainer Software University
Sets, Dictionaries SoftUni Team Technical Trainers Software University
Doctrine The PHP ORM SoftUni Team Technical Trainers Software University
Creating Content Defining Topic, Creating Technical Training Materials SoftUni Team Technical Trainers Software University
PHP Programming with MySQL Slide 5-1 CHAPTER 5 Manipulating Strings.
First Steps in PHP Creating Very Simple PHP Scripts SoftUni Team Technical Trainers Software University
Inheritance Class Hierarchies SoftUni Team Technical Trainers Software University
Lesson 4 String Manipulation. Lesson 4 In many applications you will need to do some kind of manipulation or parsing of strings, whether you are Attempting.
Stacks and Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
Generics SoftUni Team Technical Trainers Software University
Strings and Text Processing
/^Hel{2}o\s*World\n$/
Regular Expressions (RegEx)
Associative Arrays and Strings
Text Processing and Regex API
/^Hel{2}o\s*World\n$/
Chapter 3 Manipulating Strings PHP Programming with MySQL 2nd Edition Modified by Anita Philipp –Spring 2011.
PHP Programming 6th~19th, 12, 2015 Prof. YOON, Byeong Nam, PhD.
String functions
Data Manipulation & Regex
String functions
Presentation transcript:

Strings in PHP Working with Text in PHP Strings and String Functions Mario Peshev Technical Trainer Software University

Table of Contents 1.What Are Strings? 2.Manipulating Strings 3.Built-in String Functions 4.Regular Expressions 2

What Are Strings?

 Text string:  Contains zero or more characters surrounded by double or single quotation marks  Can be used as literal values or assigned to a variable  Can also be surrounded with single quotation marks <?php echo ' Mr. Svetlin Nakov '; $workPlace = " Software University "; echo $workPlace; ?>

What Are Strings? {2}  Single quotes are escaped when used in double quoted strings  Double quotes are escaped when used in single quoted strings <?php echo " I'm a Software Developer "; ?> <?php echo ' At "Software University" '; ?>

Manipulating Strings

String Operators  In PHP, you use two operators to combine Strings  Concatenation Operator “.”  Concatenation assignment operator “.=” <?php $homeTown = "Madan"; $currentTown = "Sofia"; $homeTownDescription = "My home town is". $homeTown; $homeTownDescription.= "But now I am in ". $currentTown; echo $homeTownDescription; ?>

Escape Characters  Added before a special purpose character follows it has a special purpose  In PHP, the escape character is the backslash \ <?php $myCourse = 'I\'m a PHP Developer'; ?>

Escape Sequence  The escape character combined with one or more other characters is called an escape sequence Escape Sequence Description \\ Insert a backslash \$ Insert a dollar sign \r Insert a carriage return \” Escape a double quotation mark \t Insert a horizontal tab \n Insert a new line

Simple and Complex String  Simple string syntax uses the value of a variable within a string by including the variable name inside a text string with double quotation marks  When variables are placed within curly braces inside of a string, it is called complex string syntax <?php $popularName = "Pesho"; echo "Hello $popularName"; ?> <?php $popularName = "Pesho"; echo "Hello {$popularName}"; ?>

Simple and Complex String{2}  When variables are placed within curly braces inside of a string, it is called complex string syntax <?php $popularName = "Pesho"; echo "Hello {$popularName}"; ?>

Manipulating Strings Live Demo

Built-in String Functions

Counting Characters  The most commonly used string counting function is the strlen() function  returns the total number of characters in a string <?php $name = "Software University"; echo strlen($name); ?> Output : 11

Counting Words  The str_word_count() function returns the number of words in a string  Pass the str_word_count() function a literal string or the name of a string variable whose words you want to count <?php $countries = "Bulgaria, Brazil, Italy, USA, Germany"; echo " String contains ". str_word_count($countries). " countries. "; ?> String contains 5 countries.

Counting Strings Live Demo

Finding Characters and Substrings  There are two types of string search and extraction functions:  Functions that return a numeric position in a text string  strpos() - Performs a case-sensitive search and returns the position of the first occurrence of one string in another string <?php $countries = "Brazil, Italy, Bulgaria, USA, Germany"; $bulgaria = "Bulgaria"; echo "Position of Bulgaria is: ". strpos($countries, $bulgaria); ?> Position of Bulgaria is: 15

Extracting Characters and Substrings  Functions that return a character or substring  strstr() - Function starts searching at the beginning of a string  strstr($input, $search, true) - Function starts searching at the end of a string  Both functions return a substring from the specified characters to the end of the string <?php $countries = "Brazil, Italy, Bulgaria, USA, Germany"; $bulgaria = "Bulgaria"; echo "String from Bulgaria to end: ". strstr($countries, $bulgaria); ?> String from Bulgaria to End: Bulgaria, USA, Germany

Extracting Characters and Substrings {2}  substr() - To extract characters from the beginning or middle of a string  You pass to the substr() function a text string along with the starting and ending positions of the substring you want to extract <?php $ = $nameEnd = strpos($ , echo "The name portion of the address is: ". substr($ , 0,$nameEnd); ?> The name portion of the address is: nakov

Finding And Extracting Live Demo

String Replacing  The str_replace() and str_ireplace() functions both accept three arguments:  The string you want to search for  A replacement string  The string in which you want to replace characters <?php $ = $new = str_replace("bignakov", "juniornakov", $ ); echo $new ; ?>

Trim  Trim - Strip whitespace (or other characters) from the beginning and end of a string  This function returns a string with whitespace stripped from the beginning and end of $boo.  Also have:  ltrim() – trim from beginning of a string  rtrin() – trim from end of a string <?php $boo = " foo "; echo "After trim " trim($boo); ?> After trim “foo”

Case Changing  strtolower() - Make a string lowercase  strtoupper() - Make a string uppercase <?php $boo = "FOO"; echo strtolower($boo); ?> foo <?php $boo = "foo"; echo strtoupper($boo); ?> FOO

Converting String to Array  The str_split() function splits each character in a string into an array element  The length argument represents the number of characters you want assigned to each array element $array = str_split(string[, length]);

Converting String to Array{2}  The explode() function splits a string into an indexed array at a specified separator <?php $presidents = "Georgi Pyrvanov;Jelio Jelev;Petyr Stoqnov;Rosen Pleveneliev;"; $presidentAsArray = explode( ";“, $presidents); print_r( $presidentAsArray); ?> Array ( [0] => Georgi Pyrvanov [1] => Jelio Jelev [2] => Petyr Stoqnov [3] => Rosen Pleveneliev )

explode() Function  Does not separate a string at each character that is included in the separator argument  Evaluates the characters in the separator argument as a substring  If you pass to the explode() function an empty string as the separator argument, the function returns a value of false

Converting Array to String  Implode() - Combines an array’s elements into a single string, separated by specified characters <?php $presidents = ["Georgi Pyrvanov", "Jelio Jelev", "Petyr Stoqnov", "Rosen Pleveneliev"]; $presidentAsString = implode(";", $presidents); echo $presidentAsString; ?> Georgi Pyrvanov;Jelio Jelev;Petyr Stoqnov;Rosen Pleveneliev

String <> Array Live Demo

String Comparison Functions  The strcasecmp() function performs a case-insensitive comparison of strings  The strcmp() function performs a case-sensitive comparison of strings  Both functions accept two arguments representing the strings you want to compare  Most string comparison functions compare strings based on their ASCII values

String Comparison Functions Example <?php $fName = "Nakov"; $fNameSmall = "nakov"; echo "Case insensitive\n"; echo strcasecmp($fName, $fNameSmall). "\n"; echo "Case sensitive\n"; echo strcmp($fName, $fNameSmall); ?> Case insensitive 0 Case sensitive

More comparing functions  strnatcmp(), strncasecmp(), levenshtein(), metaphone(), similar_text(), soundex(), strnatcasecmp()

String Comparing Live Demo

Regular Expressions

 It is usually possible to use a combination of various built-in PHP functions to achieve what you want.  However, sometimes this gets complicated and we turn to Regular Expressions.  Regular expressions are a concise (but complicated!) way of pattern matching  Define a pattern used to validate or extract data from a string

Some definitions  Definition of the pattern (the ‘Regular Expression’):   PHP functions to do something with data and regular expression:  preg_match(), preg_replace()

Regex: Delimiters  The regex definition is always bracketed by delimiters, usually a ‘/’: pattern: ’/php/’; Matches: ‘php’, ‘I love php’, ‘phpphp’ Doesn’t match: ‘PHP’, ‘I love ph’

Regex: Character groups  A regex is matched character-by-character. You can specify multiple options for a character using square brackets: $regex = ’/p[huo]p/’; Matches: ‘php’, ’pup’, ‘pop’ Doesn’t match: ‘phup’, ‘ppp’, ‘pHp’

Regex: Predefined Classes  A regex is matched character-by-character. You can specify multiple options for a character using square brackets: \d Matches a single character that is a digit (0-9) \s Matches any whitespaces character (include tabs and line breaks) \w Matches any alphanumeric character (A-Z, 0-9) or underscore

Regex: the Dot  The special dot character matches any character except for a line break: $regex = ’/p.p/’; Matches: ‘php’, ’p&p’, ‘p(p’, ‘p3p’, ‘p$p’ Doesn’t match: ‘PHP’, ‘phhp’

Regex: Repetition  There are a number of special characters that indicate the character group may be repeated: ? Zero or 1 times * Zero or more times + 1 or more times {a, b} Between a and b times

Regex: Anchors  So far, we have matched anywhere within a string. We can change this behavior by using anchors: ^ Start of the string $ End of string

Regular Expressions Live Demo

43  All about simple strings  Manipulating Strings  Escaping, Operators  Built-in String Functions  Most popular functions in PHP  Regular Expressions  Regex Pattern  preg_match(), preg_replace() Summary

? ? ? ? ? ? ? ? ? PHP & MySQL

License  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" licenseCreative Commons Attribution- NonCommercial-ShareAlike 4.0 International  Attribution: this work may contain portions from  "PHP Manual" by The PHP Group under CC-BY licensePHP ManualCC-BY  "PHP and MySQL Web Development" course by Telerik Academy under CC-BY-NC-SA licensePHP and MySQL Web DevelopmentCC-BY-NC-SA 45

Free Software University  Software University Foundation – softuni.orgsoftuni.org  Software University – High-Quality Education, Profession and Job for Software Developers  softuni.bg softuni.bg  Software Facebook  facebook.com/SoftwareUniversity facebook.com/SoftwareUniversity  Software YouTube  youtube.com/SoftwareUniversity youtube.com/SoftwareUniversity  Software University Forums – forum.softuni.bgforum.softuni.bg