delete string from string php

php: Delete specific index from string?

I want to be able to specify an index in a string and remove it.

I have the following:

I want to remove the 4th index ( o in Hello). Here would be the end result:

5 Answers 5

This is a generic way to solve it:

Basically, replace the part of the string before from the index onwards with the part of the string that’s adjacent.

This php specific of working with strings also bugged me for a while. Of course natural solution is to use string functions or use arrays but this is slower than directly working with string index in my opinion. With the following snippet issue is that in memory string is only replaced with empty � and if you have comparison or something else this is not good option. Maybe in future version we will get built in function to remove string indexes directly who knows.

Personal I like dealing with arrays.

(Sorry about lack of code brackets putting this up via my phone)

I think can create a function and call it like this

Not the answer you’re looking for? Browse other questions tagged php string or ask your own question.

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.16.40224

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

How can I remove part of a string in PHP? [closed]

Want to improve this question? Update the question so it’s on-topic for Stack Overflow.

How can I remove part of a string?

Example string: «REGISTER 11223344 here»

How can I remove «11223344» from the above example string?

9 Answers 9

If you’re specifically targetting «11223344», then use str_replace :

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

So you could write the code as:

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

Assuming 11223344 is not constant:

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

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

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.

Читайте также:  фрамир двери установка видео

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

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

Источник

Remove new lines from string and replace with one empty space

Want to remove all new lines from string.

I’ve this regex, it can catch all of them, the problem is I don’t know with which function should I use it.

$string should become:

20 Answers 20

You have to be cautious of double line breaks, which would cause double spaces. Use this really efficient regular expression:

Multiple spaces and newlines are replaced with a single space.

Edit: As others have pointed out, this solution has issues matching single newlines in between words. This is not present in the example, but one can easily see how that situation could occur. An alternative is to do the following:

A few comments on the accepted answer:

With these modifications, the code would be:

You could get away with str_replace() on this one, although the code doesn’t look as clean:

You should use str_replace for its speed and using double quotes with an array

I’m not sure if this has any value against the already submitted answers but I can just as well post it.

Escape sequence \R matches a generic newline

PCRE regex replacements can be done using preg_replace: http://php.net/manual/en/function.preg-replace.php

replace series of newlines with an empty string:

or you probably want to replace newlines with a single space:

I was surprised to see how little everyone knows about regex.

Strip newlines in php is

Источник

Remove a string from the beginning of a string

I have a string that looks like this:

How can I remove the first bla_ ; but only if it’s found at the beginning of the string?

11 Answers 11

Plain form, without regex:

Takes: 0.0369 ms (0.000,036,954 seconds)

Takes: 0.1749 ms (0.000,174,999 seconds) the 1st run (compiling), and 0.0510 ms (0.000,051,021 seconds) after.

Profiled on my server, obviously.

You can use regular expressions with the caret symbol ( ^ ) which anchors the match to the beginning of the string:

Here’s an even faster approach:

I think substr_replace does what you want, where you can limit your replace to part of your string: http://nl3.php.net/manual/en/function.substr-replace.php (This will enable you to only look at the beginning of the string.)

Читайте также:  запрет на инфообмен lite билайн что это

You could use the count parameter of str_replace ( http://nl3.php.net/manual/en/function.str-replace.php ), this will allow you to limit the number of replacements, starting from the left, but it will not enforce it to be at the beginning.

Nice speed, but this is hard-coded to depend on the needle ending with _. Is there a general version? – toddmo Jun 29 at 23:26

On my quite old home PC:

This will remove first match wherever it is found i.e., start or middle or end.

now does what you want.

Remove www. from beginning of string, this is the easiest way (ltrim)

Источник

str_replace

(PHP 4, PHP 5, PHP 7, PHP 8)

str_replace — Replace all occurrences of the search string with the replacement string

Description

This function returns a string or an array with all occurrences of search in subject replaced with the given replace value.

Parameters

If search or replace are arrays, their elements are processed first to last.

The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles.

The replacement value that replaces found search values. An array may be used to designate multiple replacements.

The string or array being searched and replaced on, otherwise known as the haystack.

If passed, this will be set to the number of replacements performed.

Return Values

This function returns a string or an array with the replaced values.

Examples

Example #1 Basic str_replace() examples

Example #2 Examples of potential str_replace() gotchas

Notes

Replacement order gotcha

Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements. See also the examples in this document.

This function is case-sensitive. Use str_ireplace() for case-insensitive replace.

See Also

User Contributed Notes 34 notes

A faster way to replace the strings in multidimensional array is to json_encode() it, do the str_replace() and then json_decode() it, like this:

>
?>

This method is almost 3x faster (in 10000 runs.) than using recursive calling and looping method, and 10x simpler in coding.

Note that this does not replace strings that become part of replacement strings. This may be a problem when you want to remove multiple instances of the same repetative pattern, several times in a row.

If you want to remove all dashes but one from the string ‘-aaa—-b-c——d—e—f’ resulting in ‘-aaa-b-c-d-e-f’, you cannot use str_replace. Instead, use preg_replace:

Be careful when replacing characters (or repeated patterns in the FROM and TO arrays):

Читайте также:  Как запрограммировать сон который хочешь увидеть

To make this work, use «strtr» instead:

Feel free to optimize this using the while/for or anything else, but this is a bit of code that allows you to replace strings found in an associative array.

$string = ‘I like to eat an apple with my dog in my chevy’ ;

// Echo: I like to eat an orange with my cat in my ford
?>

Here is the function:

Be aware that if you use this for filtering & sanitizing some form of user input, or remove ALL instances of a string, there’s another gotcha to watch out for:

// Remove all double characters
$string=»1001011010″;
$string=str_replace(array(«11″,»00″),»»,$string);
// Output: «110010»

$string=» ml> Malicious code html> etc»;
$string=str_replace(array(» «,» «),»»,$string);
// Output: » Malicious code etc»

This is what happens when the search and replace arrays are different sizes:

To more clearly illustrate this, consider the following example:

The following function utilizes array_combine and strtr to produce the expected output, and I believe it is the most efficient way to perform the desired string replacement without prior replacements affecting the final result.

This strips out horrible MS word characters.

Just keep fine tuning it until you get what you need, you’ll see ive commented some out which caused problems for me.

There could be some that need adding in, but its a start to anyone who wishes to make their own custom function.

There is an «invisible» character after the †for the right side double smart quote that doesn’t seem to display here. It is chr(157).

[] = ‘“’ ; // left side double smart quote
$find [] = ‘”’ ; // right side double smart quote
$find [] = ‘‘’ ; // left side single smart quote
$find [] = ‘’’ ; // right side single smart quote
$find [] = ‘…’ ; // elipsis
$find [] = ‘—’ ; // em dash
$find [] = ‘–’ ; // en dash

$replace [] = ‘»‘ ;
$replace [] = ‘»‘ ;
$replace [] = «‘» ;
$replace [] = «‘» ;
$replace [] = «. » ;
$replace [] = «-» ;
$replace [] = «-» ;

nikolaz dot tang at hotmail dot com’s solution of using json_encode/decode is interesting, but a couple of issues to be aware of with it.

json_decode will return objects, where arrays are probably expected. This is easily remedied by adding 2nd parameter ‘true’ to json_decode.

Might be worth mentioning that a SIMPLE way to accomplish Example 2 (potential gotchas) is to simply start your «replacements» in reverse.

So instead of starting from «A» and ending with «E»:

Источник

Образовательный портал