Get string between two strings

45,309

Solution 1

You can just explode it:

<?php
$string = 'reply-234-private';
$display = explode('-', $string);

var_dump($display);
// prints array(3) { [0]=> string(5) "reply" [1]=> string(3) "234" [2]=> string(7) "private" }

echo $display[1];
// prints 234

Or, use preg_match

<?php
$string = 'reply-234-private';
if (preg_match('/reply-(.*?)-private/', $string, $display) === 1) {
    echo $display[1];
}

Solution 2

Have a look at explode() function

something like this:

$myString = 'reply-234-private';

$myStringPartsArray = explode("-", $myString);

$answer = $myStringPartsArray[1];

Solution 3

This article show you, How to get of everything string between two tags or two strings.

http://okeschool.com/articles/312/string/how-to-get-of-everything-string-between-two-tag-or-two-strings

<?php
 // Create the Function to get the string
 function GetStringBetween ($string, $start, $finish) {
    $string = " ".$string;
    $position = strpos($string, $start);
    if ($position == 0) return "";
    $position += strlen($start);
    $length = strpos($string, $finish, $position) - $position;
    return substr($string, $position, $length);
}
?>

in case your question, you can try this :

$string1='reply-234-private';
echo GetStringBetween ($string1, "-", "-")

or we can use any 'identifier string' for grab the string between the identifier string. for example:

echo GetStringBetween ($string1, "reply-", "-private")

Solution 4

Use php's inbuilt regex support functions preg_match_all

this would help, suppose you want the array of strings(keys) between @@ in following example, where '/' doesn't fall in-between, you can built new example with different start an end variable

function getInbetweenStrings($start, $end, $str){
    $matches = array();
    $regex = "/$start([a-zA-Z0-9_]*)$end/";
    preg_match_all($regex, $str, $matches);
    return $matches[1];
}

$str = "C://@@ad_custom_attr1@@/@@upn@@/@@samaccountname@@";
$str_arr = getInbetweenStrings('@@', '@@', $str);

print_r($str_arr);

Solution 5

$myString = 'reply-234-private';
echo str_replace('-','',filter_var($myString,FILTER_SANITIZE_NUMBER_INT));

That should do the job.

Share:
45,309
Thanh Nguyen
Author by

Thanh Nguyen

not much

Updated on July 18, 2022

Comments

  • Thanh Nguyen
    Thanh Nguyen almost 2 years

    My string is: "reply-234-private", i want to get the number after "reply-" and before "-private", it is "234". I have tried with following code but it returns an empty result:

    $string = 'reply-234-private';
    $display = preg_replace('/reply-(.*?)-private/','',$string);
    echo $display;