For some reason, I want to remove the leftmost number inside the whole string.
Here are the example:
0abc > abc
23abc > abc
123abc456 > abc456
123ab1ab123 > ab1ab123
99abc1a1a4 > abc1a1a4
Is it possible do in php?
I tried to use:
$words = preg_replace('/[0-9]+[a-z]/', '', $file);
but it will remove both the number and the first alphabet.
You can just use an anchor and remove the [a-z] part from your regex:
$words = preg_replace('/^[0-9]+/', '', $file);
and if you dont like Rizier123 aswer:
$words = ltrim('123ab1ab123','0123456789');
or
$words = ltrim('123ab1ab123','0..9');
trims all numbers from left, probably faster than are regular expression also
Related
For example, if I want to get rid of the repeating numeric suffix from the end of an expression like this:
some_text_here_1
Or like this:
some_text_here_1_5
and I want finally receive something like this:
some_text_here
What's the best and flexible solution?
$newString = preg_replace("/_?\d+$/","",$oldString);
It is using regex to match an optional underscore (_?) followed by one or more digits (\d+), but only if they are the last characters in the string ($) and replacing them with the empty string.
To capture unlimited _ numbers, just wrap the whole regex (except the $) in a capture group and put a + after it:
$newString = preg_replace("/(_?\d+)+$/","",$oldString);
If you only want to remove a numberic suffix if it is after an underscore (e.g. you want some_text_here14 to not be changed, but some_text_here_14 to be changed), then it should be:
$newString = preg_replace("/(_\d+)+$/","",$oldString);
Updated to fix more than one suffix
Strrpos is far better than regex on such a simple string problem.
$str = "some_text_here_13_15";
While(is_numeric(substr($str, strrpos($str, "_")+1))){
$str = substr($str,0 , strrpos($str, "_"));
}
Echo $str;
Strrpos finds the last "_" in str and if it's numeric remove it.
https://3v4l.org/OTdb9
Just to give you an idea of what I mean with regex not being a good solution on this here is the performance.
Regex:
https://3v4l.org/Tu8o2/perf#output
0.027 seconds for 100 runs.
My code with added numeric check:
https://3v4l.org/dkAqA/perf#output
0.003 seconds for 100 runs.
This new code performs even better than before oddly enough, regex is very slow. Trust me on that
You be the judge on what is best.
First you'll want to do a preg_replace() in order to remove all digits by using the regex /\d+/. Then you'll also want to trim any underscores from the right using rtrim(), providing _ as the second parameter.
I've combined the two in the following example:
$string = "some_text_here_1";
echo rtrim(preg_replace('/\d+/', '', $string), '_'); // some_text_here
I've also created an example of this at 3v4l here.
Hope this helps! :)
$reg = '#_\d+$#';
$replace = '';
echo preg_replace($reg, $replace, $string);
This would do
abc_def_ghi_123 > abc_def_ghi
abc_def_1 > abc_def
abc_def_ghi > abc_def_ghi
abd_def_ > abc_def_
abc_123_def > abd_123_def
in case of abd_def_123_345 > abc_def
one could change the line
$reg = '#(?:_\d+)+$#';
Hi I want to remove a characters using preg_replace in php so i have this code here which i want to remove the whole characters, letters and numbers except the last digit(s) which has dash(-) symbol followed by a digits so here's my code.
echo preg_replace('/(.+)(?=-[0-9])|(.+)/','','asdf1245-10');
I expect the result will be
-10
the problem is above is not working very well. I checked the pattern using http://www.regextester.com/ it seems like it works, but on the other side http://www.phpliveregex.com/ doesn't work at all. I don't know why but anyone who can help to to figure it out?
Thanks a lot
Here is a way to go:
echo preg_replace('/^.+?(-[0-9]+)?$/','$1','asdf1245-10');
Output:
-10
and
echo preg_replace('/^.+?(-[0-9]+)?$/','$1','asdf124510');
Output:
<nothing>
My first thinking is to use explode in this case.. make it simple like the following code.
$string = 'asdf1245-10';
$array = explode('-', $string);
end($array);
$key = key($array);
$result = '-' . $array[$key];
$result => '-10';
An other way:
$result = preg_match('~\A.*\K-\d+\z~', $str, $m) ? $m[0] : '';
pattern details:
\A # start of the string anchor
.* # zero or more characters
\K # discard all on the left from match result
-\d+ # the dash and the digits
\z # end of the string anchor
echo preg_replace('/(\w+)(-\w+)/','$2', 'asdf1245-10');
I've been wondering, is it possible to group every 2 words using regex? For 1 word i use this:
((?:\w'|\w|-)+)
This works great. But i need it for 2 (or even more words later on).
But if I use this one:
((?:\w'|\w|-)+) ((?:\w'|\w|-)+) it will make groups of 2 but not really how i want it. And when it encounters a special char it will start over.
Let me give you an example:
If I use it on this text: This is an . example text using & my / Regex expression
It will make groups of
This is
example text
regex expression
and i want groups like this:
This is
is an
an example
example text
text using
using my
my regex
regex expression
It is okay if it resets after a . So that it won't match hello . guys together for example.
Is this even possible to accomplish? I've just started experimenting with RegEx so i don't quite know the possibilities with this.
If this isn't possible could you point me in a direction that I should take with my problem?
Thanks in advance!
Regex is an overkill for this. Simply collect the words, then create the pairs:
$a = array('one', 'two', 'three', 'four');
$pairs = array();
$prev = null;
foreach($a as $word) {
if ($prev !== null) {
$pairs[] = "$prev $word";
}
$prev = $word;
}
Live demo: http://ideone.com/8dqAkz
try this
$samp = "This is an . example text using & my / Regex expression";
//removes anything other than alphabets
$samp = preg_replace('/[^A-Z ]/i', "", $samp);
//removes extra spaces
$samp = str_replace(" "," ",$samp);
//the following code splits the sentence into words
$jk = explode(" ",$samp);
$i = sizeof($jk);
$j = 0;
//this combines words in desired format
$array="";
for($j=0;$j<$i-1;$j++)
{
$array[] = $jk[$j]." ".$jk[$j+1];
}
print_r($array);
Demo
EDIT
for your question
I've changed the regex like this: "/[^A-Z0-9-' ]/i" so it doesn't
mess up words like 'you're' and '9-year-old' for example. But by doing
this when there is a seperate - or ' in my text, it will treat those
as a seperate words. I know why it does this but is it preventable?
change the regex like this
preg_replace('/[^A-Z0-9 ]+[^A-Z0-9\'-]/i', "", $samp)
Demo
First, strip out non-word characters (replace \W with '') Then perform your match. Many problems can be made simpler by breaking them down. Regexes are no exception.
Alternatively, strip out non-word characters, condense whitespace into single spaces, then use explode on space and array_chunk to group your words into pairs.
There are a lot of questions on removing leading and trailing 0s but i couldn't find a way to remove all 0s except trailing 0s (leading 0 or in any other place other than the end).
100010 -> 110
010200 -> 1200
01110 -> 1110
any suggestions ?
Try
echo preg_replace('/0+([1-9])/', '$1', $str);
You can use the regex [0]+(?=[1-9]) to find the zeros (using positive lookahead) and preg_replace to replace them with an empty string (assuming the number is already in string form).
$result = preg_replace("#[0]+(?=[1-9])#", "", "100010");
See it in action here
You want to replace all zeroes that are not at the end of the string.
You can do that with a little regular expressions with a so called negative look-ahead, so only zeros match to be replaced that are not at the end of the string:
$actual = preg_replace('/0+(?!$|0)/', '', $subject);
The $ symbolizes the end of a string. 0+ means one or more zeroes. And that is greedy, meaning, if there are two, it will take two, not one. That is important to not replace at the end. But also it needs to be written, that no 0 is allowed to follow for what is being replaced.
Quite like you formulated your sentence:
a way to remove all 0s except trailing 0s (leading 0 or in any other place other than the end).
That is: 0+(?!$|0). See http://www.regular-expressions.info/lookaround.html - Demo.
The other variant would be with atomic grouping, which should be a little bit more straight forward (Demo):
(?>0+)(?!$)
You can use regex as others suggested, or trim. Count the trailing 0's, strip all 0's, then add the trailing 0's back.
$num = 10100;
$trailing_cnt = strlen($num)-strlen(trim($num, "0"));
$num = str_replace('0','',$num).str_repeat('0', $trailing_cnt);
// original string
$string = '100010';
// remember trailing zeros, if any
$trailing_zeros = '';
if (preg_match('/(0+)$/', $string, $matches)) {
$trailing_zeros = $matches[1];
}
// remove all zeros
$string = str_replace('0', '', $string);
// add trailing ones back, if they were found before
$string .= $trailing_zeros;
here is a solution. there shoud be prettier one, but that works also.
$subject = "010200";
$match = array();
preg_match("/0*$/",$subject,$match);
echo preg_replace("/0*/","",$subject).$match[0];
You can use regexes to do what you want:
if(preg_match('/^(0*)(.*?)(0*)$/',$string,$match)) {
$string = $match[1] . str_replace('0','',$match[2]) . $match[3];
}
Not the prettiest but it works...
$str = "01110";
if(substr($str,-1) == 0){
$str = str_replace("0","",$str)."0";
}else{
$str = str_replace("0","",$str);
}
echo $str; // gives '1110'
Here is my problem:
Using preg_replace('#\b(word)\b#','****',$text);
Where in text I have word\word and word, the preg_replace above replaces both word\word and word so my resulting string is ***\word and ***.
I want my string to look like : word\word and ***.
Is this possible? What am I doing wrong???
LATER EDIT
I have an array with urls, I foreach that array and preg_replace the text where url is found, but it's not working.
For instance, I have http://www.link.com and http://www.link.com/something
If I have http://www.link.com it also replaces http://www.link.com/something.
You are effectively specifying that you don't want certain characters to count as word boundary. Therefore you need to specify the "boundaries" yourself, something like this:
preg_replace('#(^|[^\w\\])(word)([^\w\\]|$)#','**',$text);
What this does is searches for the word surrounded by line boundaries or non-word characters except the back slash \. Therefore it will match .word, but not .word\ and not `\word. If you need to exclude other characters from matching, just add them inside the brackets.
You could just use str_replace("word\word", "word\word and"), I dont really see why you would need to use a preg_replace in your case given above.
Here is a simple solution that doesn't use a regex. It will ONLY replace single occurances of 'word' where it is a lone word.
<?php
$text = "word\word word cat dog";
$new_text = "";
$words = explode(" ",$text); // split the string into seperate 'words'
$inc = 0; // loop counter
foreach($words as $word){
if($word == "word"){ // if the current word in the array of words matches the criteria, replace it
$words[$inc] = "***";
}
$new_text.= $words[$inc]." ";
$inc ++;
}
echo $new_text; // gives 'word\word *** cat dog'
?>