How can I remove part of a string in PHP?

PhpString

Php Problem Overview


How can I remove part of a string?

Example string: "REGISTER 11223344 here"

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

Php Solutions


Solution 1 - Php

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

// str_replace($search, $replace, $subject)
echo str_replace("11223344", "","REGISTER 11223344 here");

Solution 2 - Php

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().

Solution 3 - Php

Assuming 11223344 is not constant:

$string="REGISTER 11223344 here";
$s = explode(" ", $string);
unset($s[1]);
$s = implode(" ", $s);
print "$s\n";

Solution 4 - Php

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"

Solution 5 - Php

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

Solution 6 - Php

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.

Solution 7 - Php

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.

Solution 8 - Php

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

Solution 9 - Php

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"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsiddharthView Question on Stackoverflow
Solution 1 - PhpDominic RodgerView Answer on Stackoverflow
Solution 2 - PhpdhoratView Answer on Stackoverflow
Solution 3 - Phpghostdog74View Answer on Stackoverflow
Solution 4 - Phpuser8588978View Answer on Stackoverflow
Solution 5 - PhpTravisOView Answer on Stackoverflow
Solution 6 - PhpUmair JabbarView Answer on Stackoverflow
Solution 7 - PhpMAChitgarhaView Answer on Stackoverflow
Solution 8 - Phparango_86View Answer on Stackoverflow
Solution 9 - PhpElitmiarView Answer on Stackoverflow