I am trying to replace all occurrences of '/ /' in a string with '/'. I can't seem to find the right regex expression to match the string to replace, however.
Currently, I have preg_replace('/\/\s\//', '/', $string); but this does not replace any occurrences of '/ /'.
To be clear, I would like to match any occurrences of a forward slash followed by whitespace followed by a forward slash. It seems that the last forward slash messes things up. I have also tried str_replace(), but to no avail.
EDIT:
The regex expression works correctly if I run it on a string like so:
echo(preg_replace('/\/\s?\//m', '/', ".... . -.-- / / .... ---")); and I get the output: .... . -.-- / .... ---. But when I run it like this:
$morse = preg_replace('/\/\s?\//m', '/', $morse); The replacement does not work. For the record, the ouput of echo($morse) before preg_replace is .... . -.-- / / .... --- and after it is the exact same. I have no idea what could be causing this, some sort of weird encoding in the $morse variable string?
Please help, this is driving me crazy. Thanks in advance!
The regex pattern you have written is correct and it will replace if the / / occurrence is found. I updated your pattern to /\/\s?\//m. You can try the following way.
$re = '/\/\s?\//m';
$str = 'test string // test string / /';
$subst = '/';
$result = preg_replace($re, $subst, $str);
echo "The result of the substitution is ".$result;
The use of other delimiters would simplify things enormously here:
$regex = '~/\s+/~';
$replacement = '/';
$string = preg_replace($regex, $replacement, $original_string);
Note, that your original string is left untouched.
Related
I have the following code to get characters before/after the regex match:
$searchterm = 'blue';
$string = 'Here is a sentence talking about blue. This sentence talks about red.';
$regex = '/.*(.{10}\b' . $searchterm . '\b.{10}).*/si';
echo preg_replace($regex, '$1', $string);
Output: "ing about blue. This se" (expected).
When I change $searchterm = 'red', then I get this:
Output: "Here is a sentence talking about blue. This sentence talks about red."
I am expecting this: "lks about red." The same thing happens if you start at the beginning of the sentence. Is there a way to use a similar regex to not pull back the entire string when it's at the start/end?
Example of what is happening: https://sandbox.onlinephpfunctions.com/code/e500b505860ded429e78869f61dbf4128ff368b3
Converting my comment to answer so that solution is easy to find for future visitors.
You regex regex is almost correct but make sure to use a non-greedy quantifier with .{0,10} limit for surrounding substring:
$searchterm = 'blue';
$string = 'Here is a sentence talking about blue. This sentence talks about red.';
$regex = '/.*?(.{0,10}\b' . $searchterm . '\b.{0,10}).*/si';
echo preg_replace($regex, '$1', $string);
Updated Code Demo
RegEx Demo
You'd better use preg_match with .{0,10} quantifiers instead of {10},
function truncateString($searchterm){
$string = 'Here is a sentence talking about blue. This sentence talks about red.';
$regex = '/.{0,10}\b' . $searchterm . '\b.{0,10}/si';
if (preg_match($regex, $string, $m)) {
echo $m[0] . "\n";
}
}
truncateString('blue');
// => ing about blue. This se
truncateString('red');
// => lks about red.
See the PHP demo.
preg_match will find and return the first match only. The .{0,10} pattern will match zero to ten occurrences of any char (since the s modifier is used, the . matches even line break chars).
One more thing: if your $searchterm can contain special regex metacharacters, anywhere in the term, you should consider refactoring the code to
$regex = '/.{0,10}(?<!\w)' . preg_quote($searchterm, '/') . '(?!\w).{0,10}/si';
where (?<!\w) / (?!\w) are unambiguous word boundaries and the preg_quote is used to escape all special chars.
The code below works perfectly:
$string = '(test1)';
$new = preg_replace('/^\(+.+\)+$/','word',$string);
echo $new;
Output:
word
If the code is this:
$string = '(test1) (test2) (test3)';
How to generate output:
word word word?
Why my regex do not work ?
^ and $ are anchors which means match should start from start of string and expand upto end of string
. means match anything except newline, + means one or more, by default regex is greedy in nature so it tries to match as much as possible where as we want to match ( ) so we need to change the pattern a bit
You can use
\([^)]+\)
$string = '(test1) (test2) (test3)';
$new = preg_replace('/\([^)]+\)/','word',$string);
echo $new;
Regex Demo
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 ##.
I am trying to match fx. this string
"dfsdfsdf 100.200,00"
This is what i got
[0-9\.]+
That returns
100.200
Is there anyway WITH REGEX i can just look paste the dot. So i will get:
100200
How about:
$str = 'dfsdfsdf 100.200,00';
preg_match('/(\d+)\.(\d+)/', $str, $m);
$res = $m[1] . $m[2];
echo $res,"\n";
outout:
100200
What about this:
preg_replace("/^.*?(\d+)\.(\d+).*?$/", '$1$2', "dfsdfsdf 100.200,00");
it will replace the whole string with the matched digits
working example in phpfiddle
I am new to regular expressions, and I've been trying to use it with an url, but I can't get it to work.
I have a string that is:
/plugins/plugins/plugins/plugins/plugins/plugins/
and I would like to replace all letters to the string "{char}" so that the string end up being:
/{char}/{char}/{char}/{char}/{char}/{char}/
I've tried this:
<?php
$pattern = '#(/)([a-z\_]+)(/)#';
$replacement = '$1{char}$3';
$string = '/plugins/plugins/plugins/plugins/plugins/plugins/';
echo preg_replace($pattern, $replacement, $string);
?>
But this code is resulting in this:
/{char}/plugins/{char}/plugins/{char}/plugins/
What am I doing wrong?
The problem is your regex is matching /plugins/ - matching slashes at both the front and the end. Each letter is only matched by the regex once, so if a slash is matched at the end of one word it can't also be counted as the start of another. Hence, it's only matching every other one.
Try this instead:
<?php
$pattern = '#(/)([a-z\_]+)(?=/)#';
$replacement = '$1{char}';
$string = '/plugins/plugins/plugins/plugins/plugins/plugins/';
echo preg_replace($pattern, $replacement, $string);
?>
It works by using lookahead, instead of actually matching the final slash (and "consuming" it) it just checks to make sure it's there.