How to remove asterisk from this spin syntax code? - regex

here is my code it is a text spinner (synonym)
public function fetchContent($keyword)
{
$customContent = $this->getOption('custom_content_text');
$this->_setHttpStatusCode(200);
if (!$customContent)
{
$this->_setContentStatus(self::CONTENT_STATUS_NO_RESULTS);
return false;
}
if (preg_match_all('/({\*)(.*?)(\*})/', $customContent, $result))
{
if (is_array($result[0]))
{
foreach ($result[0] as $index => $group_string)
{
//replace the first or next pattern match with a replaceable token
$customContent = preg_replace('/(\{\*)(.*?)(\*\})/', '{#'.$index.'#}', $customContent, 1);
$words = explode('|', $result[2][$index]);
//clean and trim all words
$finalPhrase = array();
foreach ($words as $word)
{
if (preg_match('/\S/', $word))
{
$word = preg_replace('/{%keyword%}/i', $keyword, $word);
$finalPhrase[] = trim($word);
}
}
$finalPhrase = $finalPhrase[rand(0, count($finalPhrase) - 1)];
//now inject it back to where the token was
$customContent = str_ireplace('{#' . $index . '#}', $finalPhrase, $customContent);
}
$this->_setContentStatus(self::CONTENT_STATUS_PASSED);
}
}
return $customContent;
}
}
there is regex that request bracket like this
{*spin1|spin2|spin3*}
here is the regex from the snippet above
if (preg_match_all('/({\*)(.*?)(\*})/', $customContent, $result))
$customContent = preg_replace('/(\{\*)(.*?)(\*\})/', '{#'.$index.'#}', $customContent, 1);
i would like to remove the * to format allow just {spin1|spin2|spin3} wich is more compatible with most spinner ,
i tried with some regex that i find online
i tried to remove the * from both regex without result
thanks you very much for your help

Remove \* instead of just * – Lucas Trzesniewski

Related

Target child pages with regex

I need an regex which target all child pages of a certain group of parent pages, but NOT the parent pages them selfes.
To be more specific, I need an expression which targets:
/categoryA/XXX
/categoryB/YYY
/categoryC/ZZZ
But I do not want to include
/categoryA/
/categoryB/
/categoryC/
All help much appreciated!
Gustav
Try this one:
\/(\w+)\/([a-zA-Z]+)
I am assuming that the strings after the categories use letters only.
Input:
/categoryA/XXX
/categoryB/YYY
/categoryC/ZZZ
/categoryA/
/categoryB/
/categoryC/
Matches:
/categoryA/XXX
/categoryB/YYY
/categoryC/ZZZ
This one
([^\/]+$)
targets everything after the last slash
You could use this in an if() statement to filter out what you need, if I understand the question correctly.
Or this one:
\/category[A-Z]\/(.*)
In C#
childpage = Regex.Match(target, "/category[A-Z]/(.*)").Groups[1].Value;
In JavaScript
var myregexp = /\/category[A-Z]\/(.*)/;
var match = myregexp.exec(target);
if (match != null) {
childpage = match[1];
} else {
childpage = "";
}
In PHP
if (preg_match('%/category[A-Z]/(.*)%', $target, $groups)) {
$childpage = $groups[1];
} else {
$childpage = "";
}
In PowerShell
if ($target -match '/category[A-Z]/(.*)') {
$childpage = $matches[1]
} else {
$childpage = ''
}
In Python
match = re.search("/category[A-Z]/(.*)", target)
if match:
childpage = match.group(1)
else:
childpage = ""

Using RegEx to match URL routes

I'm building a PHP Framework for conclusion of my course, and I've stuck on a solution for match some custom routes and standard routes.
My framework's route are similar at routes of Zend Framework 1.
It's match standard routes for
/module/controller/action/param/value/param2/value2/paramn/valuen
The part of URI are optional, and the / route leads to application module, index controller and index action without params and values.
I'm stuck in some custom routes, that I define this way:
/blog/:postname/
/admin/logout/
/blog/posts/:year/:category/
/about/
That routes must match this examples URI requests.
/blog/my-first-post/
/blog/my-first-post/referenced/facebook/
/admin/logout/
/admin/logout/session-id/246753/action
/blog/posts/2013/turism/
/blog/posts/2013/turism/page/2/
But not had to match the standard routes. The custom routes must precede the standard routes.
Some examples of standard routes. Examples:
/
/application/
/application/index/
/application/index/index/
/blog/posts/view/id/3/
/admin/login/
/admin/login/logout (that one are the
/admin/blog/posts/edit/id/3/
/admin/blog/posts/edit/id/3/success/false/
The way I find to do this ellegantily is using RegEx for the matches, but I've trying to learn RegEx for more than one month and don't got it all.
PS: After match the current route, I must to bind the :variable with the related position in the REQUEST_URI.
Thank you for help.
While admittedly tempting, I wouldn't go with regex in this particular case. Even though I usually go that way. A simple loop and match would do, unless your course is setting some restrictions you have to follow.
I put together an example that should get the job done and runs in the console, just to show what i mean.
function get_route($uri){
$routes = [
'blog#show' => 'blog/:postname',
'admin#logout' => 'admin/logout',
'blog#category' => 'blog/posts/:year/:category',
'home#about' => 'about'
];
$params = [];
$uri = preg_replace('/#|\?.+/', '', $uri); // remove hash or query strings
$uri = preg_replace('/(^\/)?(\/$)?/', '', $uri); // trim slashes
$uri = explode('/', $uri);
$action = null;
foreach ($routes as $this_action => $this_route) { // loop through possible routes
$fractions = explode('/', $this_route);
if (sizeof($fractions) !== sizeof($uri)) continue; // did not match length of uri
for ($i=0; $i<sizeof($uri); $i++) { // compare each part of uri to each part of route
if (substr($fractions[$i], 0, 1) !== ':' && $fractions[$i] !== $uri[$i]) break; // not a match and not a param
if ($i === sizeof($uri)-1) { // made it to the last fraction!
$ii = 0;
foreach ($fractions as $fraction) {
if (substr($fraction, 0, 1) == ':') { // it's a param, map it!
$params[substr($fraction,1)] = $uri[$ii];
}
$ii++;
}
return ['action'=>$this_action, 'params'=>$params];
}
}
}
return false;
}
I could reach my needs with this code, a lot of tests has passed.
public function matchCustomRoute($uri)
{
if($uri == '')
{
return null;
}
$customRoutes = $this->getRoutes();
$explodeUri = explode('/', $uri);
$arrayUri = array();
foreach($explodeUri as $uriPart)
{
if($uriPart == '')
{
continue;
}
$arrayUri[] = $uriPart;
}
$countUri = count($arrayUri);
foreach($customRoutes as $key => $value)
{
$explodeRoute = explode('/',$value['route']);
$arrayRoute = array();
foreach($explodeRoute as $routePart)
{
if($routePart == '')
{
continue;
}
$arrayRoute[] = $routePart;
}
$countRoute = count($arrayRoute);
if($countRoute > $countUri)
{
continue;
}
$matches = 0;
for($i = 0 ; $i < $countRoute ; $i++)
{
$match = preg_match('/'.$arrayUri[$i].'/', '/'.$arrayRoute[$i].'/');
if($match == 0)
{
if(substr($arrayRoute[$i], 0, 1) == ':')
{
$value['params'][substr($arrayRoute[$i], 1)] = $arrayUri[$i];
}
else
{
continue;
}
}
$matches++;
}
if($matches == $countRoute)
{
return $value;
}
}
return null;
}
Thank you for help.

perl - Split string by methods within the strings

I have two questions:
First, how can I split the following string into individual strings split by the methods within the string? I tried using regex, but was unsuccessful.
$objc = "- (void)method {
NSLog(#"method");
if (1 == 1) {
//blah blah blah
}
}
- (id)otherMethodWithProperty:(NSString *)property {
NSLog(#"otherMethodWithProperty:");
return property;
}
-(id) methodWithMoreProperties: (id)property Property2:(UIView *)property2 Property3:(NSString *)property3 {
id view = property;
if (view) {
NSLog(#"%#", view);
}
return view;
}"
Second question is after splitting into individual strings, is it possible to grab each property and add it within the respective string? For example:
I take the string:
"-(id) methodWithMoreProperties: (id)property Property2:(UIView *)property2 Property3:(NSString *)property3 {
id view = property;
if (view) {
NSLog(#"%#", view);
}
return view;
}"
grab the properties "property, property2, property3" and add them within the string after the first "{" and before the last "}":
"-(id) methodWithMoreProperties: (id)property Property2:(UIView *)property2 Property3:(NSString *)property3 {
NSLog(#"%#\n%#\n%#", property, property2, property3);
id view = property;
if (view) {
NSLog(#"%#", view);
}
return view;
NSLog(#"FINISH: %#\n%#\n%#", property, property2, property3);
}"
I've been googling and testing code for hours and I've only managed, using regex, to get the method name
-(id) methodWithMoreProperties:
and add it within the string, but haven't been able to grab the properties themselves and add them after the first { and before the last }
not all was done by regex, but I think it's more readable
# split string into methods
my #methods = split /^-/m, $objc;
foreach my $method_content (#methods) {
my $method_declaration = (split /{/, $method_content, 2)[0];
my ($method_name, #properties) = $method_declaration =~ /\)\s*(\w+)/g;
if (#properties) {
my $sprintf_format = join '\n', ('%#') x #properties;
my $sprintf_values = join ', ', #properties;
my $begin_message = sprintf 'NSLog(#"%s", %s);', $sprintf_format, $sprintf_values;
my $end_message = sprintf 'NSLog(#"FINISH: %s", %s);', $sprintf_format, $sprintf_values;
$method_content =~ s/{/{\n $begin_message/;
$method_content =~ s/}\s*$/ $end_message\n}\n\n/;
}
print "-$method_content";
}
but the $end_message should be better put before the methods's return or it'll never be triggered.
You can use this pattern:
my #matches = $objc =~ /(-\s*+\([^)]++\)(?>\s*+\w++(?>:\s*+\([^)]++\)\s*+\w++)?+)*+\s*+({(?>[^{}]++|(?-1))*+}))/g;
(you only have to costumize the capturing groups as you want)

c# and regular expression

I want to get 100 and example from this string
?connect:100/username:example/
I searched in google but cannot find some useful regex patterns form my solution
Please help
try {
Regex RegexObj = new Regex(":(?<Number>\\d+)/.+?:(?<Text>\\w+)/");
Match MatchResults = RegexObj.Match(SubjectString);
while (MatchResults.Success) {
for (int i = 1; i < MatchResults.Groups.Count; i++) {
Group GroupObj = MatchResults.Groups[i];
if (GroupObj.Success) {
}
}
MatchResults = MatchResults.NextMatch();
}
} catch (ArgumentException ex) {
// Syntax error in the regular expression
}
This is the regex:
\?connect:([0-9]+)/username:([^/]*)/
You don't need to use a regex for this, use Linq:
var url = "?connect:100/username:example/";
var data = url.Substring(1, url.Length-2).Split('/')
.Select(x => x.Split(':'))
.ToDictionary(x => x[0], x => x[1]);
Console.WriteLine(data["connect"]); // 100
Console.WriteLine(data["username"]); // example
You could remove the SubString(1, url.Length-2) call if you got the string back without the starting ? and trailing /.

Regular Expression to Extract the Url out of the Anchor Tag

I want to extract the http link from inside the anchor tags? The extension that should be extracted should be WMV files only.
Because HTML's syntactic rules are so loose, it's pretty difficult to do with any reliability (unless, say, you know for absolute certain that all your tags will use double quotes around their attribute values). Here's some fairly general regex-based code for the purpose:
function extract_urls($html) {
$html = preg_replace('<!--.*?-->', '', $html);
preg_match_all('/<a\s+[^>]*href="([^"]+)"[^>]*>/is', $html, $matches);
foreach($matches[1] as $url) {
$url = str_replace('&', '&', trim($url));
if(preg_match('/\.wmv\b/i', $url) && !in_array($url, $urls))
$urls[] = $url;
}
preg_match_all('/<a\s+[^>]*href=\'([^\']+)\'[^>]*>/is', $html, $matches);
foreach($matches[1] as $url) {
$url = str_replace('&', '&', trim($url));
if(preg_match('/\.wmv\b/i', $url) && !in_array($url, $urls))
$urls[] = $url;
}
preg_match_all('/<a\s+[^>]*href=([^"\'][^> ]*)[^>]*>/is', $html, $matches);
foreach($matches[1] as $url) {
$url = str_replace('&', '&', trim($url));
if(preg_match('/\.wmv\b/i', $url) && !in_array($url, $urls))
$urls[] = $url;
}
return $urls;
}
Regex:
<a\\s*href\\s*=\\s*(?:(\"|\')(?<link>[^\"]*.wmv)(\"|\'))\\s*>(?<name>.*)\\s*</a>
[Note: \s* is used in several places to match the extra white space characters that can occur in the html.]
Sample C# code:
/// <summary>
/// Assigns proper values to link and name, if the htmlId matches the pattern
/// Matches only for .wmv files
/// </summary>
/// <returns>true if success, false otherwise</returns>
public static bool TryGetHrefDetailsWMV(string htmlATag, out string wmvLink, out string name)
{
wmvLink = null;
name = null;
string pattern = "<a\\s*href\\s*=\\s*(?:(\"|\')(?<link>[^\"]*.wmv)(\"|\'))\\s*>(?<name>.*)\\s*</a>";
if (Regex.IsMatch(htmlATag, pattern))
{
Regex r = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
wmvLink = r.Match(htmlATag).Result("${link}");
name = r.Match(htmlATag).Result("${name}");
return true;
}
else
return false;
}
MyRegEx.TryGetHrefDetailsWMV("<td><a href='/path/to/file'>Name of File</a></td>",
out wmvLink, out name); // No match
MyRegEx.TryGetHrefDetailsWMV("<td><a href='/path/to/file.wmv'>Name of File</a></td>",
out wmvLink, out name); // Match
MyRegEx.TryGetHrefDetailsWMV("<td><a href='/path/to/file.wmv' >Name of File</a></td>", out wmvLink, out name); // Match
I wouldn't do this with regex - I would probably use jQuery:
jQuery('a[href$=.wmv]').attr('href')
Compare this to chaos's simplified regex example, which (as stated) doesn't deal with fussy/complex markup, and you'll hopefully understand why a DOM parser is better than a regex for this type of problem.