201

How can I remove part of a string?

Example string: "REGISTER 11223344 here"

How can I remove "11223344" from the above example string?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
siddharth
  • 2,067
  • 2
  • 13
  • 3
  • 1
    Your question is Unclear/ambiguous. You are using the term `remove`, but it seems likely that you mean `extract` so that the targeted string can be stored in the database. – mickmackusa Jan 01 '20 at 21:58
  • 1
    @Makyen I feel pretty confident that you have vandalized the question to make many of the answers correct. Think about it: why would the OP want to save `REGISTER here` in the database? – mickmackusa Feb 27 '20 at 07:54
  • 4
    @mickmackusa remove can be synonymous with take away from, i.e. taking 11223344 out of the string, I fail to see the problem here. At worst it's ambiguous, it's certainly not "vandalized" – Nick is tired Feb 27 '20 at 09:35
  • 1
    Read the pre-vandalized version(s). @Nick https://stackoverflow.com/posts/2192170/revisions The truth will change your mind. I would be happy to see this question closed as Unclear. – mickmackusa Feb 27 '20 at 09:41
  • 2
    @mickmackusa I did... I fail to see your point. If you have such a big problem with the way it as written why not fix it yourself – Nick is tired Feb 27 '20 at 09:41
  • 1
    The OP wants to save data to the database. It is not clear what. I feel only the OP can/should clarify (rightfully earn upvotes from a clear question) - that is why I will not edit. – mickmackusa Feb 27 '20 at 09:45

9 Answers9

277

If you're specifically targetting "11223344", then use str_replace:

// str_replace($search, $replace, $subject)
echo str_replace("11223344", "","REGISTER 11223344 here");
LinusGeffarth
  • 27,197
  • 29
  • 120
  • 174
Dominic Rodger
  • 97,747
  • 36
  • 197
  • 212
144

You can use str_replace(), which is defined as:

str_replace($search, $replace, $subject)

So you could write the code as:

$subject = 'REGISTER 11223344 here' ;
$search = '11223344' ;
$trimmed = str_replace($search, '', $subject) ;
echo $trimmed ;

If you need better matching via regular expressions you can use preg_replace().

Rahul Gopi
  • 414
  • 1
  • 16
  • 31
dhorat
  • 1,509
  • 1
  • 8
  • 4
  • 2
    If one needs regex matching there is also preg_replace() http://us2.php.net/manual/en/function.preg-replace.php – Elijah Lynn Jul 11 '13 at 17:34
  • 4
    Not sure why this answer was posted, it's a lengthier duplicate of [Dominic's answer](https://stackoverflow.com/a/2192181/6225838) and a shorter duplicate of [Roland's answer](https://stackoverflow.com/a/2192217/6225838)... – CPHPython Jul 09 '18 at 09:02
26

Assuming 11223344 is not constant:

$string="REGISTER 11223344 here";
$s = explode(" ", $string);
unset($s[1]);
$s = implode(" ", $s);
print "$s\n";
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
13
str_replace(find, replace, string, count)
  • find Required. Specifies the value to find
  • replace Required. Specifies the value to replace the value in find
  • string Required. Specifies the string to be searched
  • count Optional. A variable that counts the number of replacements

As per OP example:

$Example_string = "REGISTER 11223344 here";
$Example_string_PART_REMOVED = str_replace('11223344', '', $Example_string);

// will leave you with "REGISTER  here"

// finally - clean up potential double spaces, beginning spaces or end spaces that may have resulted from removing the unwanted string
$Example_string_COMPLETED = trim(str_replace('  ', ' ', $Example_string_PART_REMOVED));
// trim() will remove any potential leading and trailing spaces - the additional 'str_replace()' will remove any potential double spaces

// will leave you with "REGISTER here"
6

When you need rule-based matching, you need to use a regular expression:

$string = "REGISTER 11223344 here";
preg_match("/(\d+)/", $string, $match);
$number = $match[1];

That will match the first set of numbers, so if you need to be more specific, try:

$string = "REGISTER 11223344 here";
preg_match("/REGISTER (\d+) here/", $string, $match);
$number = $match[1];
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
TravisO
  • 9,406
  • 4
  • 36
  • 44
  • 1
    preg_replace() would be much easier wouldn't it? http://us2.php.net/manual/en/function.preg-replace.php – Elijah Lynn Jul 11 '13 at 17:40
  • 1
    @ElijahLynn replace requires you to remove things, future changes or noise would break. Doing this via _replace but _match would continue to work. – TravisO Jul 16 '13 at 13:27
  • @TravisO well yes, but no. Those two are almost the same functions implementation wise, and **chances that future changes affect any of them are the same**. There's a same possibility of future changes on _match only, making this use invalid and _replace still working fine. Also, versioning usually is very observant to not braking previous functionality, if possible. – CT. Oct 19 '19 at 16:00
  • You don't need a capture group here. In fact, using the capture group unnecessarily bloats the `$match` array. Remove the parentheses then acces via `$match[0]`. – mickmackusa Feb 28 '20 at 04:21
4

substr() is a built-in PHP function which returns part of a string. The function substr() will take a string as input, the index form where you want the string to be trimmed, and an optional parameter is the length of the substring. You can see proper documentation and example code on substr.

Note: index for a string starts with 0.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Umair Jabbar
  • 3,596
  • 5
  • 30
  • 42
1

Dynamically, if you want to remove (a) part(s) from (a) fixed index(es) of a string, use this function:

/**
 * Removes index/indexes from a string, using a delimiter.
 * 
 * @param string $string
 * @param int|int[] $index An index, or a list of indexes to be removed from string.
 * @param string $delimiter 
 * @return string
 * @todo Note: For PHP versions lower than 7.0, remove scalar type hints (i.e. the
 * types before each argument) and the return type.
 */
function removeFromString(string $string, $index, string $delimiter = " "): string
{
    $stringParts = explode($delimiter, $string);

    // Remove indexes from string parts
    if (is_array($index)) {
        foreach ($index as $i) {
            unset($stringParts[(int)($i)]);
        }
    } else {
        unset($stringParts[(int)($index)]);
    }

    // Join all parts together and return it
    return implode($delimiter, $stringParts);
}

For your purpose:

remove_from_str("REGISTER 11223344 here", 1); // Output: REGISTER here

One of its usages is to execute command-like strings, which you know their structures.

MAChitgarha
  • 3,728
  • 2
  • 33
  • 40
  • 2
    Ghostdog already suggested an explode-implode technique, but I can't imagine entertaining such a longwinded technique for such a basic operation. – mickmackusa Jan 01 '20 at 22:06
0

The following snippet will print "REGISTER here"

$string = "REGISTER 11223344 here";

$result = preg_replace(
   array('/(\d+)/'),
   array(''),
   $string
);

print_r($result);

The preg_replace() API usage is as given below.

$result = preg_replace(
    array('/pattern1/', '/pattern2/'),
    array('replace1', 'replace2'),
    $input_string
);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
arango_86
  • 4,236
  • 4
  • 40
  • 46
  • 1
    There is absolutely no reason to pass arrays to `preg_replace()` in this case. Nor is there any benefit to using a capture group. – mickmackusa Jan 01 '20 at 21:55
  • I agree. Array is added just for convenience. It can be neglected. it will do no harm. Added capture group for excluding numbers. This is working as per the question plotted. And further modifications and fine tuning can be done based on individuals. – arango_86 Jan 09 '20 at 10:56
  • 1
    My point is, there are unnecessary inclusions in your snippet that make no sense to include. – mickmackusa Jan 09 '20 at 11:10
-1

Do the following

$string = 'REGISTER 11223344 here';

$content = preg_replace('/REGISTER(.*)here/','',$string);

This would return "REGISTERhere"

or

$string = 'REGISTER 11223344 here';

$content = preg_replace('/REGISTER (.*) here/','',$string);

This would return "REGISTER here"

Elitmiar
  • 35,072
  • 73
  • 180
  • 229
  • 4
    Wouldn't it return "REGISTER__here", with two blanks (think underscore as spaces, comment won't allow me two subsequent spaces)? Beacuse of the spaces before and after the "(.*)". – Niki Romagnoli Nov 26 '14 at 07:56
  • 9
    This answer is AT LEAST 100% wrong. Proof: https://3v4l.org/LDLEM why does this answer have 15 UVs? – mickmackusa Feb 27 '20 at 07:47