Last active
February 15, 2018 17:47
-
-
Save AlbertoMonteiro/c42417bb769f604d09beaa69da03885b to your computer and use it in GitHub Desktop.
Nurble PHP vs C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
using System.Linq; | |
using System.Text.RegularExpressions; | |
class Nurblizador | |
{ | |
private static string[] _nouns = File.ReadAllText("nouns.txt").Split("\n"); | |
static string Nurble(string text) | |
{ | |
var pattern = Regex.Split(text.ToLower(), "[^a-z]") | |
.Where(w => !string.IsNullOrWhiteSpace(w)) | |
.Distinct() | |
.Join(_nouns, n => n, n => n, (w, n) => $@"\b{n}\b") | |
.Aggregate((a,b) => $"{a}|{b}"); | |
var replacement = @"<span class=""nurble"">nurble</span>"; | |
return Regex.Replace(text.ToUpper(), pattern, replacement, RegexOptions.IgnoreCase).Replace("\n", "<br>"); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function nurble($text) | |
{ | |
$nouns = file('nouns.txt', FILE_IGNORE_NEW_LINES); | |
$isMatch = (bool) preg_match_all('/\b[a-zA-Z]+\b/', $text, $matches); | |
if ($isMatch === true) { | |
$words = array_unique( | |
array_filter($matches[0], function ($word) use ($nouns) { | |
return in_array($word, $nouns) === false; | |
}) | |
); | |
$pattern = sprintf('/(\b)%s(\b)/', implode('(\b)|(\b)', $words)); | |
$replacement = '\1<span class="nurble">nurble</span>\2'; | |
$text = preg_replace($pattern, $replacement, $text); | |
} | |
return str_replace("\n", '<br>', $text); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment