get string between two words
Here we are discussing the method to get a string between two words or two characters. As we know that we have several string functions which are useful while we are performing this type of task. This can be done by using these string functions :
strpos, strlen and substr
Now, here I am discussing a function in which we use these string functions beautifully to derive the required results. Take an example string for more understanding.
"ticket checker event (silver)"
It is our string and we want to get the string between “(” and “)” that is “silver”. So, for this we need to use the function which is here :
<?php function get_string_part($sunil_string, $starting_part, $ending_part){ $sunil_string = " ".$sunil_string; $initial = strpos($sunil_string,$starting_part); if ($initial == 0) return ""; $initial += strlen($starting_part); $length = strpos($sunil_string,$ending_part,$initial) - $initial; return substr($sunil_string,$initial,$length); } ?>
Just put the function where you are putting all your functions, like when you are working in wordpress just put the above function in your theme’s functions.php file.
To use this function just put the below mentioned code at the place where you want to show your result :
<?php $sunil_string ="ticket checker event (silver)"; echo get_string_part($sunil_string, "(", ")"); //result is "silver" //another example $new_string ="this is another test string to get my [start]money[/start]"; echo get_string_part($new_string, "[start]", "[/start]"); //result is "money" //one more example $test_string ="this is another different string example to take my very perfect match"; echo get_string_part($test_string, "very", "match"); // result is "perfect" which lies between "very" and "match" ?>
In this way you can use this function in different different ways as per your requirement. Just need to put the your complete string, starting part and sending part by which you want to fetch a string part.
This is a very useful code, you all must like it 🙂
Leave a Reply