x06265616e
x06265616e

Reputation: 864

PHP - Strip a specific string out of a string

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

Upvotes: 0

Views: 280

Answers (5)

x06265616e
x06265616e

Reputation: 864

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!

Upvotes: 0

Misch
Misch

Reputation: 10840

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

Upvotes: 3

Jens A. Koch
Jens A. Koch

Reputation: 41756

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

Upvotes: 0

MacMac
MacMac

Reputation: 35301

$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.

Upvotes: 2

Richard Harrison
Richard Harrison

Reputation: 19393

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

Upvotes: 0

Related Questions