Extract a substring between two characters in a string PHP [duplicate]
Asked Answered
G

14

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 :)

Girl answered 15/2, 2013 at 9:36 Comment(3)
You can do it in two parts: you firstly get string from $first and then parse the result till the $second character.Dunford
what do you actually want to capture? the id, the string, the = ?Terrellterrena
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, "]");Juarez
W
70

use this code

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

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

Wimberly answered 15/2, 2013 at 9:40 Comment(1)
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 for more.Vandal
P
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));
}

?>
Phuongphycology answered 8/9, 2013 at 5:52 Comment(1)
Function returns FALSE if not matched.Draftee
S
4
$String = "[modid=256]";

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

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

$id = substr($String , $Firstpos, $Secondpos);
Scopolamine answered 15/2, 2013 at 9:41 Comment(1)
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". php.net/substrUnsettled
P
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, '='))), ']')), '=]');
Phonetic answered 15/2, 2013 at 11:9 Comment(1)
be careful, when no = or ] in the $string !Gegenschein
E
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.

Enesco answered 15/2, 2013 at 9:39 Comment(0)
A
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

Arlyne answered 15/2, 2013 at 9:41 Comment(0)
I
1
$str = "[modid=256]";
preg_match('/\[modid=(?P<modId>\d+)\]/', $str, $matches);

echo $matches['modId'];
Italy answered 15/2, 2013 at 9:42 Comment(0)
J
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]"; ?

Juarez answered 15/2, 2013 at 9:48 Comment(0)
R
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

Reamonn answered 15/2, 2013 at 9:48 Comment(1)
Why you have used $result variable?Darcee
L
0

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;
?>
Laudable answered 8/6, 2021 at 13:19 Comment(0)
C
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.

Contractile answered 26/6, 2023 at 18:30 Comment(0)
M
0

I was looking for a one line solution to a situation like this.

I had a sentence that I wanted to extract the requisition number from. The number I want is "2799".

Here is what I did:

$sentence = "The order was modified and added to new requisition (REQ-2799)";
$requisition_number = ltrim(strstr(strstr($sentence,'REQ-'),')',true),'REQ-');
echo $requisition_number; // 2799

For your specific case (although it's ten years old so you've likely got it working by now)

$String = "[modid=256]";
$id = ltrim(strstr(strstr($String,'[modid='),']',true),'[modid=');
echo $id; // 256

Hope that helps :)

Melanson answered 15/6 at 4:32 Comment(0)
P
0

I know this question has several answers but I thought I could also post a concise code which can solve the issue of the OP

function get_string_between( $str, $start, $end ){
    return trim( explode( $end, explode( $start, $str )[count( explode( $start, $str ) ) - 1] )[0] );
}

 echo $id = get_string_between( "[modid=256]", "=" , "]" );

What is happening here is first splitting the string with the $start character, or the $start string, then grabbing the last element of the resulting array, for example, in our case, we have [modid=256], we are supposed to get the string between = and ], so we first split our string with = and get the last element of resulting array, so we get 256], finally we explode the remaining string whenever find the last character ] and grab the first element of the resulting array which will be 256. This example can get any string between any two strings or characters seamlessly.

If the native functions are too many we can try using the array_pop() function to get the last element of an array for example:

function get_string_between( $str, $start, $end ){
    $first_array = explode( $start, $str );
    return trim( explode( $end, array_pop( $first_array )  )[0] );
}

 echo $id = get_string_between( "[modid=256]", "=" , "]" );

Also trim is optional. By using trim() I'm able to get the spaces on both ends removed.

Also, it would be great to check if the two splitting characters or the two splitting strings exist in your initial string

DEMO

Pseudocarp answered 17/7 at 23:6 Comment(2)
This is "concise" code?!? I disagree. IMO, it is an incomprehensible one-liner that makes way too many function calls and will surely confuse future developers. Where is the educational, plain English explanation of this code? Why should someone use 5 native functions when this task can be completed with 1 native function?Toiletry
Please see my edited answerPseudocarp
R
-2

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.

Rebeccarebecka answered 15/2, 2013 at 9:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.