PHP only leave text in between particular characters - php

I have many strings that look like this:
[additional-text Sample text...]
There is always an opening bracket + additional-text + single space and a closing bracket in the end and I need to remove all of them, so that the final string would look like this:
Sample text...
Any help or guidance is much appreciated.

You can use this o get all matches within a text block:
preg_match_all("/\[additional-text (.*?)\]/",$text,$matches);
all your texts will be in $matches[1]. So that will be:
$text = "[additional-text Sample text...]dsfg fgfd[additional-text Sample text2...] foo bar adfd as ff";
preg_match_all("/\[additional-text (.*?)\]/",$str,$matches);
var_export($matches[1]);

Get the substring you want to keep as a captured group:
^\[\S+\s([^]]+)\]$
Now in the replacement, use the only captured group, \1.
Demo

You can use:
$re = '/\[\S+\s|\]/';
$str = "[additional-text Sample text...]";
$result = preg_replace($re, '', $str);
//=> Sample text...
RegEx Demo

Use substr to remove the first 17 characters. Use regex to remove the last two:
$val = '[additional-text Sample text...]';
$text = preg_replace('#\]$#', '', substr($val, 17));

you can also do this
$a = '[additional-text Sample text...]';
$a= ltrim($a,"[additional-text ");
echo $a= rtrim($a,"]");

There is no need in regex, use substr:
$s = "[additional-text Sample text...]";
echo substr($s, 17, strlen($s)-18);
Where 17 is the length of [additional-text and 18 is the same + 1 for the last ].
See PHP demo
A regex solution is also basic:
^\[additional-text (.*)]$
or - if there can be no ] before the end:
^\[additional-text ([^]]*)]$
And replace with $1 backreference. See the regex demo, and here is a PHP demo:
$result = preg_replace('~^\[additional-text (.*)]$~', "$1", "[additional-text Sample text...]");
echo $result;
Pattern details:
^ - start of string
\[ - a literal [
additional-text - literal text
(.*) - zero or more characters other than a newline as many as possible up to
]$ - a ] at the end of the string.

Related

Replace all occurrences using preg_replace

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

Regex rules in an array

Maybe it can not be solved this issue as I want, but maybe you can help me guys.
I have a lot of malformed words in the name of my products.
Some of them has leading ( and trailing ) or maybe one of these, it is same for / and " signs.
What I do is that I am explode the name of the product by spaces, and examines these words.
So I want to replace them to nothing. But, a hard drive could be 40GB ATA 3.5" hard drive. I need to process all the word, but I can not use the same method for 3.5" as for () or // because this 3.5" is valid.
So I only need to replace the quotes, when it is at the start of the string AND at end of the string.
$cases = [
'(testone)',
'(testtwo',
'testthree)',
'/otherone/',
'/othertwo',
'otherthree/',
'"anotherone',
'anothertwo"',
'"anotherthree"',
];
$patterns = [
'/^\(/',
'/\)$/',
'~^/~',
'~/$~',
//Here is what I can not imagine, how to add the rule for `"`
];
$result = preg_replace($patterns, '', $cases);
This is works well, but can it be done in one regex_replace()? If yes, somebody can help me out the pattern(s) for the quotes?
Result for quotes should be this:
'"anotherone', //no quote at end leave the leading
'anothertwo"', //no quote at start leave the trailin
'anotherthree', //there are quotes on start and end so remove them.
You may use another approach: rather than define an array of patterns, use one single alternation based regex:
preg_replace('~^[(/]|[/)]$|^"(.*)"$~s', '$1', $s)
See the regex demo
Details:
^[(/] - a literal ( or / at the start of the string
| - or
[/)]$ - a literal ) or / at the end of the string
| - or
^"(.*)"$ - a " at the start of the string, then any 0+ characters (due to /s option, the . matches a linebreak sequence, too) that are captured into Group 1, and " at the end of the string.
The replacement pattern is $1 that is empty when the first 2 alternatives are matched, and contains Group 1 value if the 3rd alternative is matched.
Note: In case you need to replace until no match is found, use a preg_match with preg_replace together (see demo):
$s = '"/some text/"';
$re = '~^[(/]|[/)]$|^"(.*)"$~s';
$tmp = '';
while (preg_match($re, $s) && $tmp != $s) {
$tmp = $s;
$s = preg_replace($re, '$1', $s);
}
echo $s;
This works
preg_replace([[/(]?(.+)[/)]?|/\"(.+)\"/], '$1', $string)

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 ##.

Removing all characters and numbers except last variable with dash symbol

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');

regexp replace between some slashes

I need help with write regex pattern for replace my variable.
Input data
strings for parse:
/hello/world/1111/2/3/4
/hello/world/2222/2/3/4
/hello/world/3333/2/3/4
/hello/world/3333
/hello/world/1111
replace value = some
Out
/hello/world/some/2/3/4
/hello/world/some/2/3/4
/hello/world/some/2/3/4
/hello/world/some
/hello/world/some
$out = preg_replace("#^/(\w+)/(\w+)/\d{4}(/.*)?$#", "/$1/$2/some$3", $in);
This will do the correct replacement for you, here a short explanation:
^ start of line
(\w+) >1 literals
\d{4} exactly 4 digits
(/.*)? anything starting with / or nothing at all
$ end of line
If they all have four digits in the part you want to replace, just do this:
$input = preg_replace("/\d{4}/", "some", $input);
If the input number is always four digits, then
$input = preg_replace("~/\d{4}(/.*)?$~", "some$1", $input);

Categories