获取两个字符串之间的内容

9

我的字符串是:"reply-234-private",我想获取"reply-"后面和"-private"之前的数字,也就是"234"。我尝试使用以下代码,但返回了空结果:

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

3
你正在使用 preg_replace(),难道你不想使用 preg_match() 吗? - user557846
6个回答

26
你可以只需使用explode函数:
<?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

或者,使用preg_match

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

非常完美,先生。这里是我用来获取GDrive UID的代码:preg_match('/id=(.*?)&export/', $gdrive2, $matches); - Salem

7

请查看explode()函数

像这样:

$myString = 'reply-234-private';

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

$answer = $myStringPartsArray[1];

7
本文将向您展示如何获取两个标签或两个字符串之间的所有字符串。请参考以下链接: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);
}
?>

如果您有问题,可以尝试以下方法:

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

或者我们可以使用任何“标识符字符串”来获取标识符字符串之间的字符串。例如:
echo GetStringBetween ($string1, "reply-", "-private")

4

使用 PHP 内置的正则表达式支持函数 preg_match_all

假设您想获取以下示例中@@之间的字符串(键)数组,其中 '/' 未在之间出现,您可以使用不同的startend变量构建新示例来实现此目的。

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

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

那应该可以完成任务。


1
如果你想在js中实现它,请尝试这个函数 -
function getStringBetween(str , fromStr , toStr){
  var fromStrIndex = str.indexOf(fromStr) == -1 ? 0 : str.indexOf(fromStr) + fromStr.length;
  var toStrIndex = str.slice(fromStrIndex).indexOf(toStr) == -1 ? str.length-1 : str.slice(fromStrIndex).indexOf(toStr) + fromStrIndex;
  var strBtween = str.substring(fromStrIndex,toStrIndex);
  return strBtween;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接