PHP - 剥开一个特定的字符串一个字符串
问题描述:
我有这个字符串的,但我需要删除特定的东西出来吧......PHP - 剥开一个特定的字符串一个字符串
原始字符串: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”。总是改变,它永远是“人 - 某事 - 某事”。
所以我使用的方法不会工作!
感谢
答
这样做的最简单快捷的方法是使用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);
答
$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
。
答
取决于你为什么要删除这些人恰恰是Substrigs ...
- 如果你总是想删除这些人恰恰是子,你可以使用
str_replace
- 如果你总是想删除的字符同样的位置,你可以使用
substr
- 如果你总是想删除两个点之间的子串,符合特定条件的,可以使用
preg_replace
答
<?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);
谢谢你们!
你能否提供一个str_replace的例子,我有点用它卡住 – x06265616e 2012-07-08 11:20:29
正如你可以在其他答案中看到的,你只需要用一个空字符串替换你想删除的子字符串。 str_replace的第一个参数是要替换的字符串数组,第二个参数是要用作替换的字符串。其实这两个参数可以是字符串或数组... – Misch 2012-07-08 11:28:40
我打了一个障碍,请参阅编辑后! – x06265616e 2012-07-08 12:16:14