PHP - Strip a specific string out of a string

旧街凉风 提交于 2019-12-12 05:32:07

问题


I've got this string, but I need to remove specific things out of it...

Original String: hr-165-34.sh-290-92.ch-215-84.hd-180-1.lg-280-64.

The string I need: sh-290-92.ch-215-84.lg-280-64.

I need to remove hr-165-34. and hd-180-1. !

EDIT: Ahh ive hit a snag!

the string always changes, so the bits i need to remove like "hr-165-34." always change, it will always be "hr-SOMETHING-SOMETHING."

So the methods im using wont work!

Thanks


回答1:


Depends on why you want to remove exactly those Substrigs...

  • If you always want to remove exactly those substrings, you can use str_replace
  • If you always want to remove the characters at the same position, you can use substr
  • If you always want to remove substrings between two dots, that match certain criteria, you can use preg_replace



回答2:


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

Info on str_replace.




回答3:


The easiest and quickest way of doing this is to use 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);



回答4:


<?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" */');
?>



回答5:


Ive figured it out!

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

Thanks guys!



来源:https://stackoverflow.com/questions/11382611/php-strip-a-specific-string-out-of-a-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!