Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract a substring between two characters in a string PHP

Tags:

php

substr

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

like image 215
Sebastian Avatar asked Feb 15 '13 09:02

Sebastian


People also ask

How can I get data between two characters in PHP?

php function getBetween($content,$start,$end){ $r = explode($start, $content); if (isset($r[1])){ $r = explode($end, $r[1]); return $r[0]; } return ''; } ?> Example: <? php $content = "Try to find the guy in the middle with this function!"; $start = "Try to find "; $end = " with this function!

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.

What is substr () in PHP and how it is used?

The substr() is a built-in function of PHP, which is used to extract a part of a string. The substr() function returns a part of a string specified by the start and length parameter. PHP 4 and above versions support this function.

Does PHP have Substr?

You can use the PHP strpos() function to check whether a string contains a specific word or not. The strpos() function returns the position of the first occurrence of a substring in a string. If the substring is not found it returns false .


3 Answers

use this code

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

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

like image 67
Yogesh Suthar Avatar answered Oct 10 '22 19:10

Yogesh Suthar


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));
}

?>
like image 28
MaxEcho Avatar answered Oct 10 '22 18:10

MaxEcho


$String = "[modid=256]";

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

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

$id = substr($String , $Firstpos, $Secondpos);
like image 28
cartina Avatar answered Oct 10 '22 20:10

cartina