Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a PHP function to pull out the string between two characters?

Tags:

php

Is there a PHP function that grabs the string in between two characters. For example, I want to know what is between the percent and dollar symbol:

%HERE$

What is the function for this?

like image 458
John Avatar asked Mar 06 '26 23:03

John


1 Answers

You could do that with a regex :

$string = 'test%HERE$glop';

$m = array();
if (preg_match('/%(.*?)\$/', $string, $m)) {
  var_dump($m[1]);
}

Will get you :

string 'HERE' (length=4)


Couple of notes :

  • The $ in the pattern has the be escaped, as it has a special meaning (end of string)
  • You want to match everything : .*
    • that's between % and $
    • But in non-gready mode : .*?
  • And you want that captured -- hence the () arround it.
like image 79
Pascal MARTIN Avatar answered Mar 09 '26 12:03

Pascal MARTIN