PHP regular expression replace beginning and end of string if match exists - php

could you please help me on this problem
I want in PHP to replace the begining and the end of a string if match exists, as example:
source strings :
tr_abcdef_lang or tr_abcdef or tr_abcdef_cba
I want to replace the string to have it like this:
fk_abcdef or fk_abcdef_cba
I mean if strings ends with _lang or _language to remove it, and at the begining replace everything before the first _ with fk.
So more examples :
tr_abcdef => fk_abcdef
tr_abcdef_language => fk_abcdef
x_abc_cba => fk_abc_cba
x_abc_cba_lang => fk_abc_cba
t_tablename_languages => fk_tablename

i solve your regex problem
$pattern = "/^([a-zA-Z]+?)_(\w+?)([_trans|_translation|_languages]*?)$/i";
$replacement = 'fk_$2';
$fk_field_name = preg_replace($pattern,$replacement, "x_abc_cba_gsd_lang");
echo $fk_field_name;
my code
Try this ~(.*?)_(.*)_(.*)~si
preg_match_all( '~(.*?)_(.*)_(.*)~si', "x_abc_cba",$M);
$E='';
if($M[3][0]!="lang" and $M[3][0]!="language" and $M[3][0]!="languages"){
$E="_".$M[3][0];
}
echo ("fk_".$M[2][0].$E);
or try it without php regular expression
$String="x_abc_cba_lang";
$xp=explode("_",$String);
$xp[0]="fk";
end($xp);
$Ek=key($xp);
if($xp[$Ek]=="lang" or $xp[$Ek]=="language" or $xp[$Ek]=="languages"){
unset($xp[$Ek]);
}
echo implode("_",$xp);

Thanks for all who tried to help
i found the solutions and it looks like:
$pattern = "/^([a-zA-Z]+?)_(\w+?)(_trans|_translation|_languages)?$/i";
$replacement = 'fk_$2';
$fk_field_name = preg_replace($pattern, $replacement, $tbl_name);
Thanks again and best regards
Wael

Related

Simple task regex expression replacing any "%function test%" by test

I'm trying to find the good expression to replace any string starting with :
"%function
and ending by :
%"
by the inbetween string for example :
"%function test%" should return
test
and "%function test%","% function test%" should return :
test,test
I tried this
preg_replace('/"%function (.*)?%"/', '$1',$string);
I had great hope at first, coz my first example work great but with multiple function not so great.
For more information you can see the code and try out here (a sort of phpfiddle): http://sandbox.onlinephpfunctions.com/code/00232644b801271e2ffb2ddf4cd450ddffcb50c2
Any help would be greatly appreciated,
best regards.
By using ? outside the capturing group, you're making it optional. Instead what you want is a non-greedy * so you'll have to do. Other choice is to do ([^%]+)
preg_replace('/"%function (.*?)%"/', '$1',$string);
You can use look arounds
(?<="%function )[^%]+(?=%")
Regex Demo
preg_match_all( "/(?<=\"%function )[^%]+(?=%\")/", "\"%function test%\"", $matches);
Will produce
Array ( [0] => Array (
[0] => test
)
)
%\s*\S+\s+(\S+?)\s*%
Try this.Replace by $1.See demo.
https://regex101.com/r/wZ0iA3/8
$re = "/%\\s*\\S+\\s+(\\S+?)\\s*%/im";
$str = "%function test%\n%function test%,% function test%";
$subst = "$1";
$result = preg_replace($re, $subst, $str);

PHP regexp; extract last part of string

A column in my spreadsheet contains data like this:
5020203010101/FIS/CASH FUND/SBG091241212
I need to extract the last part of string after forwward slash (/) i.e; SBG091241212
I tried the following regular expression but it does not seem to work:
\/.*$
Any Idea?
Try this:
'/(?<=\/)[^\/]*$/'
The reason your current REGEXP is failing is because your .* directive matches slashes too, so it anchors to the first slash and gives you everything after it (FIS/CASH FUND/SBG091241212).
You need to specify a matching group using brackets in order to extract content.
preg_match("/\/([^\/]+)$/", "5020203010101/FIS/CASH FUND/SBG091241212", $matches);
echo $matches[1];
You could do it like this without reg ex:
<?php
echo end(explode('/', '5020203010101/FIS/CASH FUND/SBG091241212'));
?>
this will do a positive lookbehind and match upto a value which does not contain a slash
like this
[^\/]*?(?<=[^\/])$
this will only highlight the match . i.e. the last part of the url
demo here : http://regex101.com/r/pF8pS2
Make use of substr() with strrpos() as a look behind.
echo substr($str,strrpos($str,'/')+1); //"prints" SBG091241212
Demo
You can 'explode' the string:
$temp = explode('/',$input);
if (!empty($temp)){
$myString = $temp[count($temp)-1];
}
You can also use:
$string = '5020203010101/FIS/CASH FUND/SBG091241212';
echo basename($string);
http://www.php.net/manual/en/function.basename.php

PHP get specific string from url before and after unknown characters

I know it may sound as a common question but I have difficulty understanding this process.
So I have this string:
http://domain.com/campaign/tgadv?redirect
And I need to get only the word "tgadv". But I don't know that the word is "tgadv", it could be whatever.
Also the url itself may change and become:
http://domain.com/campaign/tgadv
or
http://domain.com/campaign/tgadv/
So what I need is to create a function that will get whatever word is after campaign and before any other particular character. That's the logic..
The only certain thing is that the word will come after the word campaign/ and that any other character that will be after the word we are searching is a special one ( i.e. / or ? )
I tried understanding preg_match but really cannot get any good result from it..
Any help would be highly appreciated!
I would not use a regex for that. I would use parse_url and basename:
$bits = parse_url('http://domain.com/campaign/tgadv?redirect');
$filename = basename($bits['path']);
echo $filename;
However, if want a regex solution, use something like this:
$pattern = '~(.*)/(.*)(\?.*)~';
preg_match($pattern, 'http://domain.com/campaign/tgadv?redirect', $matches);
$filename = $matches[2];
echo $filename;
Actually, preg_match sounds like the perfect solution to this problem. I assume you are having problems with the regex?
Try something like this:
<?php
$url = "http://domain.com/campaign/tgadv/";
$pattern = "#campaign/([^/\?]+)#";
preg_match($pattern, $url, $matches);
// $matches[1] will contain tgadv.
$path = "http://domain.com/campaign/tgadv?redirect";
$url_parts = parse_url($path);
$tgadv = strrchr($url_parts['path'], '/');
You don't really need a regex to accomplish this. You can do it using stripos() and substr().
For example:
$str = '....Your string...';
$offset = stripos($str, 'campaign/');
if ( $offset === false ){
//error, end of h4 tag wasn't found
}
$offset += strlen('campaign/');
$newStr = substr($str, $offset);
At this point $newStr will have all the text after 'campaign/'.
You then just need to use a similar process to find the special character position and use substr() to strip the string you want out.
You can also just use the good old string functions in this case, no need to involve regexps.
First find the string /campaign/, then take the substring with everything after it (tgadv/asd/whatever/?redirect), then find the next / or ? after the start of the string, and everything in between will be what you need (tgadv).

Preg_match, Replace and back to string

sorry but i cant solve my problem, you know , Im a noob.
I need to find something in string with preg_match.. then replace it with new word using preg_replace, that's ok, but I don't understand how to put replaced word back to that string.
This is what I got
$text ='zda i "zda"';
preg_match('/"(\w*)"/', $text);
$najit = '/zda/';
$nahradit = 'zda';
$o = '/zda/';
$a = 'if';
$ahoj = preg_replace($najit, $nahradit, $match[1]);
Please, can you help me once again?
You can use e.g. the following code utilizing negative lookarounds to accomplish what you want:
$newtext = preg_replace('/(?<!")zda|zda(?!")/', 'if', $text)
It will replace any occurence of zda which is not enclosed in quotes on both sides (i.e. in U"Vzda"W the zda will be replaced because it is not enclosed directly into quotes).

Having problems getting a PHP regex to match

Here is my problem. It's probably a simple fix. I have a regex that I am using to replace a url BBCode. What I have right now that is not working looks like this.
<?php
$input_string = '[url=www.test.com]Test[url]';
$regex = '/\[url=(.+?)](.+?)\[\/url]/is';
$replacement_string = '$2';
echo preg_replace($regex, $replacement_string, $input_string);
?>
This currently outputs the original $input_string, while I would like it to output the following.
Test
What am I missing?
<?php
$input_string = '[url=www.test.com]Test[/url]';
$regex = '/\[url=(.+?)\](.+?)\[\/url\]/is';
$replacement_string = '$2';
echo preg_replace($regex, $replacement_string, $input_string);
?>
In your BBCode string, I closed the
[url] properly.
I escaped a ] in the regex (not sure if that was an actual problem).
Note that [url]http://example.org[/url] is also a valid way to make a link in BBCode.
You should listen to the comments suggesting you use an existing BBCode parser.
Change this line as follows:
$regex = '/[url=(.+?)](.+?)[url]/is';
OK, the formatting is not proper. While I figure it out, see this: http://pastebin.com/6pF0FEbA

Categories