PHP-从字符串中提取一个特定的字符串


PHP - Strip a specific string out of a string

我有这个字符串,但我需要从中删除特定的东西…

原始字符串:hr-165-34.sh-290-92.ch-215-84.hd-180-1.lg-280-64

我需要的字符串:sh-290-92.ch-215-84.lg-280-64

我需要删除hr-165-34. and hd-180-1。!

编辑:啊,我遇到了一个障碍!

字符串总是会改变,所以我需要删除的比特,比如"hr-165-34"。总是会改变的,它总是"hrSomethingSomething"。

所以我用的方法是行不通的!

感谢

这取决于您为什么要删除那些Substigs。。。

  • 如果您总是想删除这些子字符串,可以使用str_replace
  • 如果您总是想删除相同位置的字符,可以使用substr
  • 如果您总是想删除两个点之间符合特定条件的子字符串,可以使用preg_replace
$str = 'hr-165-34.sh-290-92.ch-215-84.hd-180-1.lg-280-64';
$new_str = str_replace(array('hr-165-34.', 'hd-180-1.'), '', $str);

str_replace的信息。

最简单、最快捷的方法是使用str_replace

$ostr = "hr-165-34.sh-290-92.ch-215-84.hd-180-1.lg-280-64";
$nstr = str_replace("hr-165-34.","",$ostr);
$nstr = str_replace("hd-180-1.","",$nstr);
<?php    
$string = 'hr-165-34.sh-290-92.ch-215-84.hd-180-1.lg-280-64';
// define all strings to delete is easier by using an array
$delete_substrings = array('hr-165-34.', 'hd-180-1.');
$string = str_replace($delete_substrings, '', $string);

assert('$string == "sh-290-92.ch-215-84.lg-280-64" /* Expected result: string = "sh-290-92.ch-215-84.lg-280-64" */');
?>

我想通了!

$figure = $q['figure']; // hr-165-34.sh-290-92.ch-215-84.hd-180-1.lg-280-64
$s = $figure;
$matches = array();
$t = preg_match('/hr(.*?)'./s', $s, $matches);
$s = $figure;
$matches2 = array();
$t = preg_match('/hd(.*?)'./s', $s, $matches2);
$s = $figure;
$matches3 = array();
$t = preg_match('/ea(.*?)'./s', $s, $matches3);
$str = $figure;
$new_str = str_replace(array($matches[0], $matches2[0], $matches3[0]), '', $str);
echo($new_str);

谢谢大家!