Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Return string between two characters

I am wanting to use "keywords" within a large string. These keywords start and end using my_keyword and are user defined. How, within a large string, can I search and find what is between the two * characters and return each instance?

The reason it might change it, that parts of the keywords can be user defined, such as page_date_Y which might show the year in which the page was created.

So, again, I just need to do a search and return what is between those * characters. Is this possible, or is there a better way of doing this if I don't know the "keyword" length or what i might be?

like image 994
Nic Hubbard Avatar asked Jan 12 '10 07:01

Nic Hubbard


People also ask

How can I get data between two characters in PHP?

$between = preg_replace('/(. *)BEFORE(. *)AFTER(. *)/s', '\2', $string);

How to get value between two strings in php?

Syntax: $arr=explode(separator, string). This will return an array which will contain the string split on the basis of the separator.

How do you find the string between two characters?

To get a substring between two characters:Get the index after the first occurrence of the character. Get the index of the last occurrence of the character. Use the String. slice() method to get a substring between the 2 characters.


1 Answers

<?php
// keywords are between *
$str = "PHP is the *best*, its the *most popular* and *I* love it.";    
if(preg_match_all('/\*(.*?)\*/',$str,$match)) {            
        var_dump($match[1]);            
}
?>

Output:

array(3) {
  [0]=>
  string(4) "best"
  [1]=>
  string(12) "most popular"
  [2]=>
  string(1) "I"
}
like image 149
codaddict Avatar answered Oct 27 '22 07:10

codaddict