PHP preg_replace expect digits after a dash - php

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

Related

How to remove a character from a string only if it follows a number?

I have several rows of data that are in address format, I want to remove the house number from each address.
So far I have been able to remove the number using:
<?php
$string = '25a Test Lane';
if (preg_match("/[0-9]/", $string)) {
$string = preg_replace("/[0-9]/", "", $string);
}
?>
$string then becomes 'a Test Lane' - but how would I go about removing 'a' as well? Bearing in mind the 'a' could be any letter following a number. I'd want to remove any character that immediately follows the number (no space in between).
You can use
trim(preg_replace("/\b\d+[a-zA-Z]*\b/", "", $string))
trim(preg_replace("/\b\d+[a-zA-Z]?\b/", "", $string))
Here is the regex demo. NOTE: if you only want to allow a single letter after the number, replace * with ? in [a-zA-Z]*.
Details:
\b - a word boundary
\d+ - one or more digits
[a-zA-Z]* - zero or more ASCII letters
[a-zA-Z]? - one or zero ASCII letters
\b - a word boundary.
See the PHP demo:
$string = '25a Test Lane';
$string = trim(preg_replace("/\b\d+[a-zA-Z]*\b/", "", $string));
echo $string;
// => Test Lane

Php make spaces in a word with a dash

I have the following string:
$thetextstring = "jjfnj 948"
At the end I want to have:
echo $thetextstring; // should print jjf-nj948
So basically what am trying to do is to join the separated string then separate the first 3 letters with a -.
So far I have
$string = trim(preg_replace('/s+/', ' ', $thetextstring));
$result = explode(" ", $thetextstring);
$newstring = implode('', $result);
print_r($newstring);
I have been able to join the words, but how do I add the separator after the first 3 letters?
Use a regex with preg_replace function, this would be a one-liner:
^.{3}\K([^\s]*) *
Breakdown:
^ # Assert start of string
.{3} # Match 3 characters
\K # Reset match
([^\s]*) * # Capture everything up to space character(s) then try to match them
PHP code:
echo preg_replace('~^.{3}\K([^\s]*) *~', '-$1', 'jjfnj 948');
PHP live demo
Without knowing more about how your strings can vary, this is working solution for your task:
Pattern:
~([a-z]{2}) ~ // 2 letters (contained in capture group1) followed by a space
Replace:
-$1
Demo Link
Code: (Demo)
$thetextstring = "jjfnj 948";
echo preg_replace('~([a-z]{2}) ~','-$1',$thetextstring);
Output:
jjf-nj948
Note this pattern can easily be expanded to include characters beyond lowercase letters that precede the space. ~(\S{2}) ~
You can use str_replace to remove the unwanted space:
$newString = str_replace(' ', '', $thetextstring);
$newString:
jjfnj948
And then preg_replace to put in the dash:
$final = preg_replace('/^([a-z]{3})/', '\1-', $newString);
The meaning of this regex instruction is:
from the beginning of the line: ^
capture three a-z characters: ([a-z]{3})
replace this match with itself followed by a dash: \1-
$final:
jjf-nj948
$thetextstring = "jjfnj 948";
// replace all spaces with nothing
$thetextstring = str_replace(" ", "", $thetextstring);
// insert a dash after the third character
$thetextstring = substr_replace($thetextstring, "-", 3, 0);
echo $thetextstring;
This gives the requested jjf-nj948
You proceeding is correct. For the last step, which consists in inserting a - after the third character, you can use the substr_replace function as follows:
$thetextstring = 'jjfnj 948';
$string = trim(preg_replace('/\s+/', ' ', $thetextstring));
$result = explode(' ', $thetextstring);
$newstring = substr_replace(implode('', $result), '-', 3, false);
If you are confident enough that your string will always have the same format (characters followed by a whitespace followed by numbers), you can also reduce your computations and simplify your code as follows:
$thetextstring = 'jjfnj 948';
$newstring = substr_replace(str_replace(' ', '', $thetextstring), '-', 3, false);
Visit this link for a working demo.
Oldschool without regex
$test = "jjfnj 948";
$test = str_replace(" ", "", $test); // strip all spaces from string
echo substr($test, 0, 3)."-".substr($test, 3); // isolate first three chars, add hyphen, and concat all characters after the first three

Operation on string in PHP. Remove part of string

How can i remove part of string from example:
##lang_eng_begin##test##lang_eng_end##
##lang_fr_begin##school##lang_fr_end##
##lang_esp_begin##test33##lang_esp_end##
I always want to pull middle of string: test, school, test33. from this string.
I Read about ltrim, substr and other but I had no good ideas how to do this. Becouse each of strings can have other length for example :
'eng', 'fr'
I just want have string from middle between ## and ##. to Maye someone can help me? I tried:
foreach ($article as $art) {
$title = $art->titl = str_replace("##lang_eng_begin##", "", $art->title);
$art->cleanTitle = str_replace("##lang_eng_end##", "", $title);
}
But there
##lang_eng_end##
can be changed to
##lang_ger_end##
in next row so i ahvent idea how to fix that
If your strings are always in this format, an explode way looks easy:
$str = "##lang_eng_begin##test##lang_eng_end## ";
$res = explode("##", $str)[2];
echo $res;
You may use a regex and extract the value in between the non-starting ## and next ##:
$re = "/(?!^)##(.*?)##/";
$str = "##lang_eng_begin##test##lang_eng_end## ";
preg_match($re, $str, $match);
print_r($match[1]);
See the PHP demo. Here, the regex matches a ## that is not at the string start ((?!^)##), then captures into Group 1 any 0+ chars other than newline as few as possible ((.*?)) up to the first ## substring.
Or, replace all ##...## substrings with `preg_replace:
$re = "/##.*?##/";
$str = "##lang_eng_begin##test##lang_eng_end## ";
echo preg_replace($re, "", $str);
See another demo. Here, we just remove all non-overlapping substrings beginning with ##, then having any 0+ chars other than a newline up to the first ##.

Finding and replacing all words that ends with 'ing'

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

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.

Categories