Easiest way of getting part of string given to its sub-string or character
function that returns part of string after specified sub-string
1
2
3
4
5
6
7
| function strafter( $string , $substring ) { $pos = strpos ( $string , $substring ); if ( $pos === false) return $string ; else return ( substr ( $string , $pos + strlen ( $substring ))); } |
function that returns part of string before specified sub-string
1
2
3
4
5
6
7
| function strbefore( $string , $substring ) { $pos = strpos ( $string , $substring ); if ( $pos === false) return $string ; else return ( substr ( $string , 0, $pos )); } |
Usage:
1
2
3
4
5
6
| $myvar = 'Anti,Christ,World' ; $myvar = strafter( $myvar , ',' ); //$myvar = 'Christ,World' echo $myvar ; //result 'Christ,World' echo strbefore( $myvar , ',' ); //result 'Christ' |
Full Script:
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
| <?php function strafter( $string , $substring ) { $pos = strpos ( $string , $substring ); if ( $pos === false) return $string ; else return ( substr ( $string , $pos + strlen ( $substring ))); } function strbefore( $string , $substring ) { $pos = strpos ( $string , $substring ); if ( $pos === false) return $string ; else return ( substr ( $string , 0, $pos )); } $myvar = 'Anti,Christ,World' ; $myvar = strafter( $myvar , ',' ); //$myvar = 'Christ,World' echo $myvar ; //result 'Christ,World' echo strbefore( $myvar , ',' ); //result 'Christ' ?> |
0 comments:
Post a Comment