Finding and replacing all words that ends with 'ing' - php

I'm trying to find and replace all words that ends with 'ing'. How would I do that?
$text = "dreaming";
if (strlen($text) >= 6) {
if (0 === strpos($text, "ing"))
//replace the last 3 characters of $text <---not sure how to do this either
echo $text;
echo "true";
}
Result:
null
Want Result:
dream
true

You could also use substr
$text = "dreaming";
if (substr($text, (strlen($text) - 3), 3) === 'ing') {
$text = substr($text, 0, (strlen($text) - 3));
}
echo $text;

This should work for replacing ing at the end of words whilst ignoring stuff starting with Ing as well as words with ing in the middle of them.
$output = preg_replace('/(\w)ing([\W]+|$)/i', '$1$2', $input);
Updated to reflect change specified in comments.

You could use two regexs depending on what you are trying to accomplish your question is a bit ambiguous.
echo preg_replace('/([a-zA-Z]+)ing((:?[\s.,;!?]|$))/', '$1$2', $text);
or
echo preg_replace('/.{3}$/', '', $text);
The first regex looks for word characters before an ing and then punctuation marks, white spaces, or the end of the string. The second just takes off the last three characters of the string.

You can use regex and word boundaries.
$str = preg_replace('/\Bing\b/', "", $str);
\B (non word boundary) matches where word characters are sticking together.
Be aware it substitutes king to k. See demo at regex101

Related

preg replace everything BUT digits over 5 in length

I have a string:
3 pk. Ready-Dough White Loaves Included $3.99 - 47500 - 00892, 48101
I want to keep only groups of digits longer than 5 characters, and if possible, any dashes or commas between them.
e.g.
47500-00892,48101
My first step was to strip out groups of digits < 4:
preg_replace('/\d{1,4}/', '', $string);
My thinking was "replace any block of digits from 1 to 4 with nothing", but that doesn't do exactly what I thought. Maybe I'm just missing an operator?
Then I was going to strip out all letters and all punctuation except , and -. In my example I would've been left with a starting - because of it being in a string, but a trim() would've been fine to clean that up.
Any help is appreciated!
Had I been patient for 5 more minutes, I would've found the answer: \b
For some reason, working with digits didn't trigger that I needed to use 'word boundaries'.
$string = preg_replace('/\b\d{1,4}\b/', '', $string);
$string = preg_replace('/[^0-9-,]/', '', $string);
$string = trim($string, ',-');
Since there's no reason to perform a replacement, you can use preg_match_all to take what you want and reduce the result array:
$re = '/\d{5,}(?:(?=\s*([-,])\s*\d{5}))?/';
$str = '3 pk. Ready-Dough White Loaves Included $3.99 - 47500 - 00892, 48101';
if ( preg_match_all($re, $str, $matches, PREG_SET_ORDER) ) {
$result = array_reduce($matches, function ($c,$i) { return $c . implode('', $i); });
echo $result;
}

PHP preg_replace expect digits after a dash

Hi i'm trying to replace all digits or numbers in a string except digits after dash by blank space
For example I have this :
$string = "1234 Example-1234";
And I want to have only "Example-1234"
I tried preg_replace('/\-?\d+/','',$string); but even digits after dash are replaced
Edited: Thanks everyone i tried all of your answers and it works well !
If you want to just skip all digits preceded with - and remove all others, use
'~-\d+(*SKIP)(*F)|\d+~'
See the regex demo
Note you would like to trim the result or add \s* around \d+ pattern.
Pattern details:
-\d+(*SKIP)(*F) - match -, 1+ digits and skip this match
| - or
\d+ - 1 or more digits
See the PHP demo:
$str = '1234 Example-1234';
$res = preg_replace('/-\d+(*SKIP)(*F)|\s*\d+/', '', $str);
echo trim($res); // => Example-1234
The solution using regex negative lookbehind assertion (?<!a)b:
$str = "1234 Example-1234";
$str = preg_replace('/(?<![0-9-])\d+/', '', $str);
print_r($str);
The output:
Example-1234
Because you are looking for words that contain a dash, you can achieve this by to splitting the string via spaces, loop through the array values until you find a string with a dash, and then output from there onwards.
$string = "1234 Example-1234";
$words = explode(" ", $string);
foreach($words as $word) {
if (strpos($word, '-') !== false) {
echo $word;
break; // delete this line if there are multiple instances of words with dashes in your string
}
}
This will output Example-1234.
You can see a working example here
ONLINE Regex tester : https://regex101.com/r/ykUWfM/3
<?php
$string = "1234 Example-1234";
echo preg_replace('/-(\d+)/','',$string);
?>
OUTPUT: before - convert into string
1234 Example
NOTE: Before - its get the string before dash -
OR
Demo: https://regex101.com/r/ykUWfM/2
<?php
$string = "1234 Example-1234";
echo preg_replace('/(?<![0-9-])\s*\d+/','',$string);
?>
OUTPUT:
Example-1234

PHP Regex: Remove words less than 3 characters

I'm trying to remove all words of less than 3 characters from a string, specifically with RegEx.
The following doesn't work because it is looking for double spaces. I suppose I could convert all spaces to double spaces beforehand and then convert them back after, but that doesn't seem very efficient. Any ideas?
$text='an of and then some an ee halved or or whenever';
$text=preg_replace('# [a-z]{1,2} #',' ',' '.$text.' ');
echo trim($text);
Removing the Short Words
You can use this:
$replaced = preg_replace('~\b[a-z]{1,2}\b\~', '', $yourstring);
In the demo, see the substitutions at the bottom.
Explanation
\b is a word boundary that matches a position where one side is a letter, and the other side is not a letter (for instance a space character, or the beginning of the string)
[a-z]{1,2} matches one or two letters
\b another word boundary
Replace with the empty string.
Option 2: Also Remove Trailing Spaces
If you also want to remove the spaces after the words, we can add \s* at the end of the regex:
$replaced = preg_replace('~\b[a-z]{1,2}\b\s*~', '', $yourstring);
Reference
Word Boundaries
You can use the word boundary tag: \b:
Replace: \b[a-z]{1,2}\b with ''
Use this
preg_replace('/(\b.{1,2}\s)/','',$your_string);
As some solutions worked here, they had a problem with my language's "multichar characters", such as "ch". A simple explode and implode worked for me.
$maxWordLength = 3;
$string = "my super string";
$exploded = explode(" ", $string);
foreach($exploded as $key => $word) {
if(mb_strlen($word) < $maxWordLength) unset($exploded[$key]);
}
$string = implode(" ", $exploded);
echo $string;
// outputs "super string"
To me, it seems that this hack works fine with most PHP versions:
$string2 = preg_replace("/~\b[a-zA-Z0-9]{1,2}\b\~/i", "", trim($string1));
Where [a-zA-Z0-9] are the accepted Char/Number range.

preg_replace vs trim PHP

I am working with a slug function and I dont fully understand some of it and was looking for some help on explaining.
My first question is about this line in my slug function $string = preg_replace('# +#', '-', $string); Now I understand that this replaces all spaces with a '-'. What I don't understand is what the + sign is in there for which comes after the white space in between the #.
Which leads to my next problem. I want a trim function that will get rid of spaces but only the spaces after they enter the value. For example someone accidentally entered "Arizona " with two spaces after the a and it destroyed the pages linked to Arizona.
So after all my rambling I basically want to figure out how I can use a trim to get rid of accidental spaces but still have the preg_replace insert '-' in between words.
ex.. "Sun City West " = "sun-city-west"
This is my full slug function-
function getSlug($string){
if(isset($string) && $string <> ""){
$string = strtolower($string);
//var_dump($string); echo "<br>";
$string = preg_replace('#[^\w ]+#', '', $string);
//var_dump($string); echo "<br>";
$string = preg_replace('# +#', '-', $string);
}
return $string;
}
You can try this:
function getSlug($string) {
return preg_replace('#\s+#', '-', trim($string));
}
It first trims extra spaces at the beginning and end of the string, and then replaces all the other with the - character.
Here your regex is:
#\s+#
which is:
# = regex delimiter
\s = any space character
+ = match the previous character or group one or more times
# = regex delimiter again
so the regex here means: "match any sequence of one or more whitespace character"
The + means at least one of the preceding character, so it matches one or more spaces. The # signs are one of the ways of marking the start and end of a regular expression's pattern block.
For a trim function, PHP handily provides trim() which removes all leading and trailing whitespace.

Replace only at the end of the string

echo $string can give any text.
How do I remove word "blank", only if it is the last word of the $string?
So, if we have a sentence like "Steve Blank is here" - nothing should not removed, otherwise if the sentence is "his name is Granblank", then "Blank" word should be removed.
You can easily do it using a regex. The \b ensures it's only removed if it's a separate word.
$str = preg_replace('/\bblank$/', '', $str);
As a variation on Teez's answer:
/**
* A slightly more readable, non-regex solution.
*/
function remove_if_trailing($haystack, $needle)
{
// The length of the needle as a negative number is where it would appear in the haystack
$needle_position = strlen($needle) * -1;
// If the last N letters match $needle
if (substr($haystack, $needle_position) == $needle) {
// Then remove the last N letters from the string
$haystack = substr($haystack, 0, $needle_position);
}
return $haystack;
}
echo remove_if_trailing("Steve Blank is here", 'blank'); // OUTPUTS: Steve blank is here
echo remove_if_trailing("his name is Granblank", 'blank'); // OUTPUTS: his name is Gran
Try the below code:
$str = trim($str);
$strlength = strlen($str);
if (strcasecmp(substr($str, ($strlength-5), $strlength), 'blank') == 0)
echo $str = substr($str, 0, ($strlength-5))
Don't use preg_match unless it is not required. PHP itself recommends using string functions over regex functions when the match is straightforward. From the preg_match manual page.
ThiefMaster is quite correct. A technique that doesn't involve the end of line $ regex character would be to use rtrim.
$trimmed = rtrim($str, "blank");
var_dump($trimmed);
^ That's if you want to remove the last characters of the string. If you want to remove the last word:
$trimmed = rtrim($str, "\sblank");
var_dump($trimmed);

Categories