Php 获取两个字符串之间的字符串
我的字符串是:“reply-234-private”,我想在“reply-”之后和“-private”之前得到数字,它是“234”。我尝试了以下代码,但返回的结果为空:Php 获取两个字符串之间的字符串,php,regex,preg-match,pcre,Php,Regex,Preg Match,Pcre,我的字符串是:“reply-234-private”,我想在“reply-”之后和“-private”之前得到数字,它是“234”。我尝试了以下代码,但返回的结果为空: $string = 'reply-234-private'; $display = preg_replace('/reply-(.*?)-private/','',$string); echo $display; 你可以这样做: 查看一下 大概是这样的: $myString = 'reply-234-private'; $m
$string = 'reply-234-private';
$display = preg_replace('/reply-(.*?)-private/','',$string);
echo $display;
你可以这样做:
查看一下
大概是这样的:
$myString = 'reply-234-private';
$myStringPartsArray = explode("-", $myString);
$answer = $myStringPartsArray[1];
使用php内置的正则表达式支持函数 这会有所帮助,假设您希望字符串(键)数组介于@之间,在下面的示例中,如果“/”不在两者之间,您可以使用不同的开始变量结束来构建新示例
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);
这应该可以完成这项工作。本文将向您展示如何获取两个标记或两个字符串之间的所有字符串 或者我们可以使用任何“标识符字符串”来获取标识符字符串之间的字符串。例如:
echo GetStringBetween ($string1, "reply-", "-private")
如果您想在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;
}
您正在使用preg_replace(),您不想要preg_match()吗??
$myString = 'reply-234-private';
echo str_replace('-','',filter_var($myString,FILTER_SANITIZE_NUMBER_INT));
<?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")
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;
}