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

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

Related

Matching a substring (an apostrophe) in a given word using regex

I have a server application which looks up where the stress is in Russian words. The end user writes a word жажда. The server downloads a page from another server which contains the stresses indicated with apostrophes for each case/declension like this жа'жда. I need to find that word in the downloaded page.
In Russian the stress is always written after a vowel. I've been using so far a regex that is a grouping of all possible combinations (жа'жда|жажда'). Is there a more elegant solution using just a regex pattern instead of making a PHP script which creates all these combinations?
EDIT:
I have a word жажда
The downloaded page contains the string жа'жда. (notice the
apostrophe, I do not before-hand know where the apostrophe in the
word is)
I want to match the word with apostrophe (жа'жда).
P.S.: So far I have a PHP script creating the string (жа'жда|жажда') used in regex (apostrophe is only after vowels) which matches it. My goal is to get rid of this script and use just regex in case it's possible.
If I understand your question,
have these options (d'isorder|di'sorder|dis'order|diso'rder|disor'der|disord'er|disorde'r|disorder‌​') and one of these is in the downloaded page and I need to find out which one it is
this may suit your needs:
<pre>
<?php
$s = "d'isorder|di'sorder|dis'order|diso'rder|disor'der|disord'er|disorde'r|disorder'|disorde'";
$s = explode("|",$s);
print_r($s);
$matches = preg_grep("#[aeiou]'#", $s);
print_r($matches);
running example: https://eval.in/207282
Uhm... Is this ok with you?
<?php
function find_stresses($word, $haystack) {
$pattern = preg_replace('/[aeiou]/', '\0\'?', $word);
$pattern = "/\b$pattern\b/";
// word = 'disorder', pattern = "diso'?rde'?r"
preg_match_all($pattern, $haystack, $matches);
return $matches[0];
}
$hay = "something diso'rder somethingelse";
find_stresses('disorder', $hay);
// => array(diso'rder)
You didn't specify if there can be more than one match, but if not, you could use preg_match instead of preg_match_all (faster). For example, in Italian language we have àncora and ancòra :P
Obviously if you use preg_match, the result would be a string instead of an array.
Based, on your code, and the requirements that no function is called and disorder is excluded. I think this is what you want. I have added a test vector.
<pre>
<?php
// test code
$downloadedPage = "
there is some disorde'r
there is some disord'er in the example
there is some di'sorder in the example
there also' is some order in the example
there is some disorder in the example
there is some dso'rder in the example
";
$word = 'disorder';
preg_match_all("#".preg_replace("#[aeiou]#", "$0'?", $word)."#iu"
, $downloadedPage
, $result
);
print_r($result);
$result = preg_grep("#'#"
, $result[0]
);
print_r($result);
// the code you need
$word = 'also';
preg_match("#".preg_replace("#[aeiou]#", "$0'?", $word)."#iu"
, $downloadedPage
, $result
);
print_r($result);
$result = preg_grep("#'#"
, $result
);
print_r($result);
Working demo: https://eval.in/207312

php preg_match replace result duplicate

I am a newbie in preg_match patterns, so I would be glad if someone could help me for next situation:
I need to replace those string:
[popup="about"]about me[/popup]
to
<a href="#PopupAbout" data-plugin-options='{"type":"inline", preloader: false}'>about me</a>
I have tried with $pattern = '/\[popup="(.*?)"\](.*?)\[\/popup\]/'; but it does not give me expected result, it give duplicated results. And how can I replace it all in a simple way!
Regards!
How about:
$str = preg_replace('~\[popup="about"\](.+?)\[/popup\]'~,
"<a href=\"#PopupAbout\" data-plugin-options='{\"type\":\"inline\", preloader: false}'>$1</a>",
$str);
Try this:
preg_match("/\[popup="(.*)"\](.*?)\[\/popup\]/", $input_line, $output_array);
I get this result:
Array
(
[0] => [popup="about"]about me[/popup]
[1] => about
[2] => about me
)
You can test it online here: http://www.phpliveregex.com/

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

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

stuck in regular expression i dont know if it is even possible or not using php preg_match_all

i have a file out of which i want a specific data below is the sample data
moduleHelper.addModule('REC');
moduleHelper.addModule('TOP');
What i want is
anything.anything('x');i.e.
moduleHelper.addModule('');
The above is what i want to be returned .
i just dont want the 'x' part exclusive of single quote.
i tried by my self and wrote a regex which is below.
/(.*)\.(.*)\(\'[^.*]\'\)/mi
it gives me nothing according to the PCRE manual the ^ inside the [ ] does negation ??
It could be done with preg_replace_callback if you feel like figuring out how all that backreferencing works, but i think this is a bit easier:
// the regex
$regex = "/(?P<FIRST>.+)?\.(?P<SECOND>.+)\('(?P<PARAM>.+)?\'\)?/mi";
$subject = <<<EOB
moduleHelper.addModule('REC');
moduleHelper.addModule('TOP');
EOB;
$matches = array();
$numberOfMatches = preg_match_all($regex, $subject, $matches, PREG_SET_ORDER);
$results = array();
foreach($matches as $match)
{
array_push($results, sprintf("%s.%s('')", $match['FIRST'], $match['SECOND']));
}
print_r($results);
// result:
Array
(
[0] => moduleHelper.addModule('')
[1] => moduleHelper.addModule('')
)
Try using the following
/^([^.]+)\.([^\(]+)/
If ^ is the first character in [ ] then it negates the other characters in the set. Where [ab] accepts either a or b, [^ab] accepts any character that is not a nor b.
Also I'm not sure what you want. You state that you do not want the 'x', but what exactly do you want?
It does do negation. [^.*], in this case, means "get on character that is not . or *. I think you want below, but I can't totally tell.
preg_match_all( "/(\w+\.\w+)(?=\([\"']\w+[\"']\);)/i", $string, $matches);
Try this one:
/([^.]*)\.([^.]*)\(.*\)/

regex question redux regarding definition list

Trying to figure out a way to throw out attributes in this data that do not have any values. Thanks for helping.
My current regex code , thanks to Tomalak looks like this
Regex find
([^=|]+)=([^|]+)(?:\||$)
Regex replace
<dt>$1</dt><dd>$2</dd>
Data looks like this
Bristle Material=|Wire Material=Steel|Dia.=4 in|Grit=|Bristle Diam=|Wire Size=0.0095 in|Arbor Diam=|Arbor Thread - TPI or Pitch=1/2 - 3/8 in|No. of Knots=|Face Width=1/2 in|Face Plate Thickness=7/16 in|Trim Length=7/8 in|Stem Diam=|Speed=6000 rpm [Max]|No. of Rows=|Color=|Hub Material=|Structure=|Tool Shape=|Applications=Cleaning rust, scale and dirt, Light Deburring, Edge Blending, Roughening for adhesion, Finish preparation prior to plating or painting|Applicable Materials=|Type=|Used With=Straight Grinders, Bench/Pedestal Grinders, Right Angle Grinders|Packing Type=|Quantity=1 per pack|Wt.=
End result should like this
<dt>Wire Material</dt><dd>Steel</dd><dt>Dia.</dt><dd>4 in</dd><dt>Wire Size</dt><dd>0.0095 in</dd>
Not this
Bristle Material=|<dt>Wire Material</dt><dd>Steel</dd><dt>Dia.</dt><dd>4 in</dd>Grit=|Bristle Diam=|<dt>Wire Size</dt><dd>0.0095 in
Here is how you can do it in PHP without using regular expressions:
$parts_list = explode('|', "Bristle Material=|Wire M....");
$parts = "";
foreach( $parts_list as $part ){
$p = explode('=', $part);
if(!empty($p[1])) $parts .= "<dt>$p[0]</dt>\n<dd>$p[1]</dd>\n";
}
echo $parts;
And here is how you can do it with regular expressions:
$parts = preg_replace(
array('/([^=|]*)=(?:\||$)/','/([^=|]*)=([^|]+)(?:\||$)/'),
array('', '<dt>$1</dt><dd>$2</dd>'),
$inputString
);
echo $parts;
Update
This is using a special replace feature of the PHP preg_replace which takes an array of regex expressions, and an array of replacement strings. The array() syntax of the function basically equates to this:
If I can match this: /([^=|]*)=(?:\||$)/ then replace it with an empty string.
If I can match this: /([^=|]*)=([^|]+)(?:\||$)/ then replace it with <dt>$1</dt><dd>$2</dd>
To test it in a Regex editor, you would run the first expression first (/([^=|]*)=(?:\||$)/) then run the second expression on the result of the first expression.
([^=|]*)=([^|]*)(?:\||$)
to skip the ones with out a value, try this:
(?:[^=|]*=|([^=|]*)=([^|]+))(?:\||$)
looks like you want preg_match here rather than preg_replace
preg_match_all('~([^|]+)=([^|\s][^|]*)~', $str, $matches, PREG_SET_ORDER);
foreach($matches as $match)
echo "<dt>{$match[1]}</dt><dd>{$match[2]}</dd>\n";

Categories