47

Is there a PHP function that can extract a phrase between 2 different characters in a string? Something like substr();

Example:

$String = "[modid=256]";

$First = "=";
$Second = "]";

$id = substr($string, $First, $Second);

Thus $id would be 256

Any help would be appreciated :)

Dalija Prasnikar
  • 27,212
  • 44
  • 82
  • 159
Sebastian
  • 505
  • 1
  • 5
  • 7
  • 1
    You can do it in two parts: you firstly get string from $first and then parse the result till the $second character. – fedorqui Feb 15 '13 at 09:37
  • what do you actually want to capture? the id, the string, the = ? – djjjuk Feb 15 '13 at 09:38
  • in such cases i usually love to explode my strings: explode("=",$String); and in a second step i would get rid of that "]" maybe through rtrim($string, "]"); – tillinberlin Feb 15 '13 at 09:39

12 Answers12

70

use this code

$input = "[modid=256]";
preg_match('~=(.*?)]~', $input, $output);
echo $output[1]; // 256

working example http://codepad.viper-7.com/0eD2ns

Yogesh Suthar
  • 30,424
  • 18
  • 72
  • 100
  • 2
    For anyone wondering: The reason index `1` of `$output` contains the text matched by the pattern inside the parenthetical is that `$output[0]` is the full text of that is matched by the pattern. `$output[1]` is the text matched by the first sub-pattern; `$output[2]` is the text matched by the second sub-pattern, and so on. See [the official documentation on `preg_match`](https://www.php.net/manual/en/function.preg-match.php) for more. – Carter Pape May 20 '19 at 01:22
28

Use:

<?php

$str = "[modid=256]";
$from = "=";
$to = "]";

echo getStringBetween($str,$from,$to);

function getStringBetween($str,$from,$to)
{
    $sub = substr($str, strpos($str,$from)+strlen($from),strlen($str));
    return substr($sub,0,strpos($sub,$to));
}

?>
MD SHAHIDUL ISLAM
  • 14,325
  • 6
  • 82
  • 89
4
$String = "[modid=256]";

$First = "=";
$Second = "]";

$Firstpos=strpos($String, $First);
$Secondpos=strpos($String, $Second);

$id = substr($String , $Firstpos, $Secondpos);
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
cartina
  • 1,409
  • 13
  • 21
  • 2
    The third argument to `substr` is `length` not ending position. If you run this, you will see that `$id` is equal to "=256]" here not "256". https://www.php.net/substr – salsbury Aug 13 '19 at 16:37
3

If you don't want to use reqular expresion, use strstr, trim and strrev functions:

// Require PHP 5.3 and higher
$id = trim(strstr(strstr($String, '='), ']', true), '=]');

// Any PHP version
$id = trim(strrev(strstr(strrev((strstr($String, '='))), ']')), '=]');
tasmaniski
  • 4,767
  • 3
  • 33
  • 65
2

Regular Expression is your friend.

preg_match("/=(\d+)\]/", $String, $matches);
var_dump($matches);

This will match any number, for other values you will have to adapt it.

Gerald Schneider
  • 17,416
  • 9
  • 60
  • 78
1

You can use a regular expression:

<?php
$string = "[modid=256][modid=345]";
preg_match_all("/\[modid=([0-9]+)\]/", $string, $matches);

$modids = $matches[1];

foreach( $modids as $modid )
  echo "$modid\n";

http://eval.in/9913

Bgi
  • 2,513
  • 13
  • 12
1
$str = "[modid=256]";
preg_match('/\[modid=(?P<modId>\d+)\]/', $str, $matches);

echo $matches['modId'];
Prasanth Bendra
  • 31,145
  • 9
  • 53
  • 73
1

I think this is the way to get your string:

<?php
function get_string_between($string, $start, $end){
    $string = ' ' . $string;
    $ini = strpos($string, $start);
    if ($ini == 0) return '';
    $ini += strlen($start);
    $len = strpos($string, $end, $ini) - $ini;
    return substr($string, $ini, $len);
}


$fullstring = '.layout { 

color: {{ base_color }} 

}

li { 

color: {{ sub_color }} 

} 

.text { 

color: {{ txt_color }}

 }

 .btn { 

color: {{ btn_color }}

 }

.more_text{

color:{{more_color}}

}';

  $parsed = get_string_between($fullstring, '{{', '}}');
  echo $parsed;
?>
Maizied Hasan Majumder
  • 1,197
  • 1
  • 12
  • 25
0

(moved from comment because formating is easier here)

might be a lazy approach, but in such cases i usually would first explode my string like this:

$string_array = explode("=",$String); 

and in a second step i would get rid of that "]" maybe through rtrim:

$id = rtrim($string_array[1], "]");

...but this will only work if the structure is always exactly the same...

-cheers-

ps: shouldn't it actually be $String = "[modid=256]"; ?

tillinberlin
  • 429
  • 4
  • 14
0

Try Regular Expression

$String =" [modid=256]";
$result=preg_match_all('/(?<=(=))(\d+)/',$String,$matches);
print_r($matches[0]);

Output

Array ( [0] => 256 )

DEMO

Explanation Here its used the Positive Look behind (?<=)in regular expression eg (?<=foo)bar matches bar when preceded by foo, here (?<=(=))(\d+) we match the (\d+) just after the '=' sign. \d Matches any digit character (0-9). + Matches 1 or more of the preceeding token

Reshil
  • 471
  • 3
  • 9
0

There's a lot of good answers here. Some of the answers related to strpos, strlen, and using delimiters are wrong.

Here is working code that I used to find the height and width of an image using delimiters, strpos, strlen, and substr.

$imageURL = https://images.pexels.com/photos/5726359/pexels-photo-5726359.jpeg?auto=compress&cs=tinysrgb&h=650&w=940;

// Get Height
$firstDelimiter = "&h=";
$secondDelimiter = "&w=";
$strPosStart = strpos($imageURL, $firstDelimiter)+3;
$strPosEnd = strpos($imageURL, $secondDelimiter)-$strPosStart;
$height = substr($imageURL, $strPosStart, $strPosEnd);
echo '<br>'.$height;


// Get Width
$firstDelimiter = "&w=";
$strPosStart = strpos($imageURL, $firstDelimiter)+3;
$strPosEnd = strlen($imageURL);
$width = substr($imageURL, $strPosStart, $strPosEnd);
echo '<br>'.$width;

Basically, define your string delimiters. You can also set them programmatically if you wish.

Then figure out where each delimiter starts and ends. You don't need to use multiple characters like I did, but make sure you have enough characters so it doesn't capture something else in the string.

It then figures out the starting and ending position of where the delimiter is found.

Substr requires the string it will be processing, the starting point, and the LENGTH of the string to capture. This is why there is subtraction done when calculating the height.

The width example uses string length instead since I know it will always be at the end of the string.

FontFamily
  • 355
  • 4
  • 13
-1

You can use a regular expression or you can try this:

$String = "[modid=256]";

$First = "=";
$Second = "]";
$posFirst = strpos($String, $First); //Only return first match
$posSecond = strpos($String, $Second); //Only return first match

if($posFirst !== false && $posSecond !== false && $posFirst < $posSecond){
    $id = substr($string, $First, $Second);
}else{
//Not match $First or $Second
}

You should read about substr. The best way for this is a regular expression.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
pacmora
  • 19
  • 2