Monday, 21 October 2013

Expression matching in php

Expression Matching in php
Expression Matching in php programming language. In this tutorials i am briefly preg_match function . preg_match function is used to take expressionmatching. expression matching basically matches pattern inside string. So, we can use this function to check whether string existinside of string or we can take more complex pattern and check whether its exists inside strings.
Code for expression matching (Screenshot1) :-
expression matching in php
expression matching (Screenshot1)
1
2
3
4
5
6
7
8
9
10
11
12
<?php
 
$string = 'This is a string.';
 
if(preg_match('/is/',$string)) {
echo 'Match Found.';
 
} else {
echo 'No match found.';
}
 
?>
Output (Screenshot2) :-
expression matching in php
expression matching (Screenshot2)
Here i am created an example to checking string inside of string. So i had variable string so, now we had to check whether we find a match inside of the string. preg_match function will tell you where the match is its just return you 1 or 0 depending on match. So, we can put in if condition and see what it returns true or false means 0 and 1. In preg_match function take 3 parameters we will take 2 parameters. Here we will searching of string which we had predefined. Here we are searching of is and whole string. You can see match found we know is there inside string.
code for expression matching (Screenshot3) :-
expression matching in php
expression matching (Screenshot3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
 
function has_space($string){
if(preg_match('/ /',$string)) {
return true;
}else {
return false;
}
}
 
$string = 'Thisdoesnthavespace';
 
if(has_space($string)) {
echo 'Has at least one space.';
} else {
echo 'Has no spaces.';
}
 
?>
Output (Screenhsot4) :-
expression matching in php
expression matching (Screenshot4)
In this example i am creating function and checking whether string had space or not. I had previous  tutorial of Basic Functions in phpplease check out about how to create functions. Here i had createdfunction named has_space($string) will put string variable and then will check whether condition is true for perg_match or false with two parameters such as space and string which we want to checkwhether its had a space or not.

Read More Extra Tutorials

No comments:

Post a Comment