str_replace leaving whitespace PHP - php

This is my variable to be altered:
$last = 'Some string 1 foobar'
and my replace statement
$last = str_replace(['1', '2'], '', $last);
and finally the output
Some string foobar
How do i get rid of the whitespace in between 'string' and 'foobar', my initial thought was that in my str_replace statement using '' as the replacement would also remove the whitespace but it doesnt.
To clarify I want to know how to make it Some string foobar and not Some stringfoobar.

A regular expression based approach is more flexible for such stuff:
<?php
$subject = 'Some string 1 foobar';
var_dump(preg_replace('/\d\s?/', '', $subject));
The output of above code is: string(18) "Some string foobar"
What does that do, how does it work? It replaces a pattern, not a fixed, literal string. Here the pattern is: any digit (\d) along with a single, potentially existing white space character (\s?).
A different, alternative approach would be that:
<?php
$subject = 'Some string 1 foobar';
var_dump(preg_replace('/(\s\d)+\s/', ' ', $subject));
This one replaces any sequence consisting of one or more occurrences of a digit preceded by a white space ((\s\d)+) along with a single white space by a single white blank character.

If you do not want to use preg_replace then you can do something like this.
$result = 'Some string 1 foobar';
$result = str_replace(['1', '2'], '', $result);
$result = str_replace(' ', ' ', $result);
However I have to admit that I like preg_replace solution more. Not sure about the benchmark though.

Related

How to match alphanumeric and symbols using PHP?

I'm working with text content in UTF8 encoding stored in variable $title.
Using preg_replace, how do I append an extra space if the $title string is ending with:
upper/lower case character
digit
symbol, eg. ? or !
This should do the trick:
preg_replace('/^(.*[\w?!])$/', "$1 ", $string);
In essence what it does is if the string ends in one of your unwanted characters it appends a single space.
If the string doesn't match the pattern, then preg_replace() returns the original string - so you're still good.
If you need to expand your list of unwanted endings you can just add them into the character block [\w?!]
Using a positive lookbehind before the end of the line.
And replace with a space.
$title = preg_replace('/(?<=[A-Za-z0-9?!])$/',' ', $title);
Try it here
You may want to try this Pattern Matching below to see if that does it for you.
<?php
// THE REGEX BELOW MATCHES THE ENDING LOWER & UPPER-CASED CHARACTERS, DIGITS
// AND SYMBOLS LIKE "?" AND "!" AND EVEN A DOT "."
// HOWEVER YOU CAN IMPROVISE ON YOUR OWN
$rxPattern = "#([\!\?a-zA-Z0-9\.])$#";
$title = "What is your name?";
var_dump($title);
// AND HERE, YOU APPEND A SINGLE SPACE AFTER THE MATCHED STRING
$title = preg_replace($rxPattern, "$1 ", $title);
var_dump($title);
// THE FIRST var_dump($title) PRODUCES:
// 'What is your name?' (length=18)
// AND THE SECOND var_dump($title) PRODUCES
// 'What is your name? ' (length=19) <== NOTICE THE LENGTH FROM ADDED SPACE.
You may test it out HERE.
Cheers...
You need
$title=preg_replace("/.*[\w?!]$/", "\\0 ", $title);

PHP String Pattern Replace

I have a set of strings like this:
Pants [+$50]
Shirts [+$10]
Jeans [+$5]
Jackets [+$100]
How can I remove the ' [xxx]' in these lines and leaving just the item name (without the trailing space)? I was told to define a regular expression, not sure how that works...
That's actually a bit of a confusing regex, since [ and ] are special characters:
$str = 'Pants [+$50]';
$str = rtrim(preg_replace('/\[[^\]]*\]/', '', $str));
// 'Pants'
Basically the partern \[[^\]]*\] means to match a literal [ followed by 0 or more characters that are not ] followed by a ]. The second string in preg_replace is what it gets replaced with. In this case the empty string since we want to remove it. Then we use rtrim to trim any trailing whitespace.
Try this one:
The RegEx
(?im)[ \t]*\[[^\]\[]+\][ \t]*$
Code
$result = preg_replace('/^(.+?)[ \t]*\[[^\][]+\][ \t]*$/im', '$1', $subject);

How to remove a string between the specific characters using regular expression in PHP?

I have string like below,
$string = "test coontevt [gallery include=\"12,24\"] first [gallery include=\"12,24\"] second";
i need to remove the string starts with [gallery to first ocuurance of it's ].
i already use this one,
$string12 = preg_replace('/[gallery.+?)+(/])/i', '', $string);
but i get empty string only.
Finally i want result for the above string is,
$string ="test coontevt first second".
How can i do this using regular expression?.
plz help me?
The character [ is a regex meta-character. TO match a literal [ you need to escape it.
$string12 = preg_replace('/\[gallery.+?\]/i', '', $string);
or
$string12 = preg_replace('/\[gallery[^\]]+\]/i', '', $string);
You need to escape the square brackets
$string12 = preg_replace('/\[gallery.+?\]/i', '', $string);
The round brackets are unnecessary so I removed them, also the quantifier between those brackets and the forward slash before the last square bracket.
To avoid multiple space in the result, I would match also the surrounding spaces and replace with 1 space.
\s+\[gallery.+?\]\s+ and replace with one space
$string12 = preg_replace('/\s+\[gallery.+?\]\s+/i', ' ', $string);
See this expression here online on Regexr
Try it like this:
$string12 = preg_replace('/\[gallery[^\]]+\]/i', '', $string);
[^\]]+ means that there can be one or more character that is not ]. And there is no need for any ( and ) if you don't want to use the backreferences.

preg_replace, string and numeric replacement

So this is a preg_replace associated question i guess,
I have a string with multiple repeating patterns
they all formated as:
some string :22: more text :12: etc
how do i replace the ":" around them with some different char?
You can do something like this:
$string = 'some string :22: more text :12: etc';
$regex = '/:(\d+):/';
$newString = preg_replace($regex, "#$1#", $string);
Note: You have to replace the '#' in the second parameter with the char you want (also different chars before and after the numbers).
Sbustitudes _ for : around numbers:
preg_replace('/:(\d+):/', '_$1_', 'some string :22: more text :12: etc');
EDIT: Misunderstood original question. However, is still a flexible option:
$result = str_replace(":22:", "tag", "some string :22: more text :12: etc");
$result = str_replace(":12:", "other_tag", $result);
Replace the ? character with your replacement character.

Removing long words regex

I would like to how can I remove long word from a string. Words greater than length n.
I tried the following:
//remove words which have more than 5 characters from string
$s = 'abba bbbbbbbbbbbb 1234567 zxcee ytytytytytytytyt zczc xyz';
echo preg_replace("~\s(.{5,})\s~isU", " ", $s);
Gives the Output (which is incorrect):
abba 1234567 ytytytytytytytyt zczc xyz
Use this regex: \b\w{5,}\b. It will match long words.
\b - word boundary
\w{5,} - alphanumeric 5 or more repetitions
\b - word boundary
<?php
//remove words which have more than 5 characters from string
$s = 'abba bbbbbbbbbbbb 1234567 zxcee ytytytytytytytyt zczc xyz';
$patterns = array(
'long_words' => '/[^\s]{5,}/',
'multiple_spaces' => '/\s{2,}/'
);
$replacements = array(
'long_words' => '',
'multiple_spaces' => ' '
);
echo trim(preg_replace($patterns, $replacements, $s));
?>
Output:
abba zczc xyz
Update, to address the issue you presented in the comments. You can do it like this:
<?php
//remove words which have more than 5 characters from string
$s = '123 ReallyLongStringComesHere 123';
$patterns = array(
'html_space' => '/ /',
'long_words' => '/[^\s]{5,}/',
'multiple_spaces' => '/\s{2,}/'
);
$replacements = array(
'html_space' => ' ',
'long_words' => '',
'multiple_spaces' => ' '
);
echo str_replace(' ', ' ', trim(preg_replace($patterns, $replacements, $s)));
?>
Output:
123 123
A better approach maybe to use regular string manipulation instead of a regex? A simple implode/explode and strlen will do nicely. Depending on the size of your string of course, but for your example it should be fine.
You're close:
preg_replace("~\w{5,}~", "", $s);
Working codepad example: http://codepad.org/c5AN1E6M
Also, you'll want to collapse multiple spaces into one:
preg_replace("~ +~", " ", $s);
Example for this one
Add the global modifier g or use preg_match_all().
Summary:
any answer starting or ending with \s will fail to remove words at the beginning and the end of string (and you should use a test string which fails with these!)
\b doesn't fail like that but it won't remove whitespaces. you can combine that what a suggested double-space remover but that won't preserve original duplicated whitespaces (this may not be a problem).
explode+implode has a nice property that it preserves duplicated whitespaces but you have to do it for every whitespace character.
an alternative for whitespace-preserving (which I haven't seen here) is to use two patterns, one starting with \b ending with \s and another one starting with \s and ending with $.

Categories