Propper Regex Pattern - php

I need to check the incoming string and leave only characters, matching:
small case a-z letters
_ character
any numbers
only one dot (first one)
$string = 'contDADdas7.6.asdASDj_##e1!Ddd__aa#S.txt';
$pattern = "/[a-z_0-9]+/";
preg_match_all("/[a-z_0-9]+/", $name, $result);
echo implode('', $result[0]);
has to be
contdas7.6asdj_e1dd__aatxt
It matches first three points, how can I take only one first dot ?

You can try this:
$string = strrev($string);
$string = preg_replace('~[^a-z0-9_.]++|\.(?![^.]*$)~', '', $string);
$string = strrev($string);
An other way:
$strs = explode('.', $string);
if (count($strs)>1) {
$strs[0] .= '.' . $strs[1];
unset($strs[1]);
}
$string = preg_replace('~[^a-z0-9_.]++~', '', implode('', $strs));

<?php
$str = "contDADdas7.6.asdASDj_##e1!Ddd__aa#S.txt";
preg_match_all("/[a-z_0-9\.]+/", $str, $match);
$newstr = implode("", $match[0]);
echo substr_replace(str_replace(".", "", $newstr), ".", strpos($newstr, "."), 0);
Output:
contdas7.6asdj_e1dd__aatxt

Related

Replace word with stars (exact length)

am trying to replace a word in a string BUT i want to get the word found in the function and replace it with a word with stars with the exact length ?
Is this possible or do i need to do this in some other way ?
$text = "Hello world, its 2018";
$words = ['world', 'its'];
echo str_replace($words, str_repeat("*", count(FOUND) ), $text);
You could use a regular expression to do that :
$text = preg_replace_callback('~(?:'.implode('|',$words).')~i', function($matches){
return str_repeat('*', strlen($matches[0]));
}, $text);
echo $text ; // "Hello *****, *** 2018"
You also could secure this using preg_quote before to use preg_replace_callback() :
$words = array_map('preg_quote', $words);
EDIT : The following code is another way, that use a foreach() loop, but prevent unwanted behaviors (replacing part of words), and allows multi-bytes characters:
$words = ['foo', 'bar', 'bôz', 'notfound'];
$text = "Bar&foo; bAr notfoo, bôzo bôz :Bar! (foo), notFOO and NotBar or 'bar' foo";
$expt = "***&***; *** notfoo, bôzo *** :***! (***), notFOO and NotBar or '***' ***";
foreach ($words as $word) {
$text = preg_replace_callback("~\b$word\b~i", function($matches) use ($word) {
return str_ireplace($word, str_repeat('*', mb_strlen($word)), $matches[0]);
}, $text);
}
echo $text, PHP_EOL, $expt ;
Another approach:
$text = "Hello world, its 2018";
$words = ['world', 'its'];
$f = function($value) { return str_repeat("*", strlen($value)) ; } ;
$replacement = array_map($f, $words);
echo str_replace($words, $replacement, $text);
You can try this :
$text = "Hello world, its 2018";
$words = ['world', 'its'];
// Loop through your word array
foreach ($words as $word) {
$length = strlen($word); // length of the word you want to replace
$star = str_repeat("*", $length); // I build the new string ****
$text = str_replace($word, $star, $text); // I replace the $word by the new string
}
echo $text; // Hello *****, *** 2018
Is it what you are looking for?
You can go like this..
$text = "Hello crazy world, its 2018";
$words = ['world', 'its'];
array_walk($words,"replace_me");
function replace_me($value,$key)
{
global $text;
$text = str_replace($value,str_repeat("*",strlen($value)),$text);
}
echo $text;
$text = "Hello world, its 2018";
$words = ['world', 'its'];
// Loop through your word array
foreach ($words as $word) {
$length = strlen($word); // length of the word you want to replace
$star = str_repeat("*", $length); // I build the new string ****
$text = str_replace($word, $star, $text); // I replace the $word by the new string
}
echo $text; // Hello *****, *** 2018

Remove word from a string

I have a csv file that contains company names. I would want to match it against my database. In order to have a cleaner and nearer matches, I am thinking of eliminating some company suffixes like 'inc', ' inc', ', inc.' or ', inc'. Here's my sample code:
$string = 'Inc Incorporated inc.';
$wordlist = array("Inc","inc."," Inc.",", Inc.",", Inc"," Inc");
foreach ($wordlist as &$word) {
$word = '/\b' . preg_quote($word, '/') . '\b/';
}
$string = preg_replace($wordlist, '', $string);
$foo = preg_replace('/\s+/', ' ', $string);
echo $foo;
My problem here is that the 'inc.' doesn't get removed. I'm guessing it has something to do with the preq_quote. But I just can't figure out how to solve this.
Try this :
$string = 'Inc incorporated inc.';
$wordlist = array("Inc","inc.");
foreach ($wordlist as $word) {
$string =str_replace($word, '', $string);
}
echo $string;
OR
$string = 'Inc Incorporated inc.';
$wordlist = array("Inc","inc.");
$string = str_replace($wordlist, '', $string);
echo $string;
This will output as 'corporated'...
If you want "Incorporated" as result, make the "I" is small.. and than run my above code (first one)...
Try this. It may involve type juggling at some point, but will have your desired result
$string = 'Inc Incorporated inc.';
$wordlist = array('Inc', 'inc.');
$string_array = explode(' ', $string);
foreach($string_array as $k => $a) {
foreach($wordlist as $b) {
if($b == $a){
unset($string_array[$k]);
}
}
$string_array = implode('', $string_array);
You can use this
$string = 'Inc Incorporated inc.';
$wordlist = array("Inc "," inc.");
$foo = str_replace($wordlist, '', $string);
echo $foo;
Run this code here
This will work for any number of elements in array...
$string = 'Inc Incorporated inc.';
$wordlist = array("Inc");
foreach($wordlist as $stripped)
$string = preg_replace("/\b". preg_quote($stripped,'/') ."(\.|\b)/i", " ", $string) ;
$foo = preg_replace('/\s+/', ' ', $string);
echo $foo;

Replace empty spaces with ### from Text between " " in a string in PHP

I have a string like this one text more text "empty space".
How can I replace the space in "empty space" and only this space with ###?
$string = 'text more text "empty space"';
$search = 'empty space';
str_replace($search, 'empty###space', $string);
How about this, with no regular expressions:
$text = 'foo bar "baz quux"';
$parts = explode('"', $text);
$inQuote = false;
foreach ($parts as &$part) {
if ($inQuote) { $part = str_replace(' ', '###', $part); }
$inQuote = !$inQuote;
}
$parsed = implode('"', $parts);
echo $parsed;
$somevar = "empty space";
$pattern = "/\s/";
$replacement = "###";
$somevar2 = preg_replace($pattern, $replacement, $somevar);
echo $somevar2;
$string = "My String is great";
$replace = " ";
$replace_with = "###";
$new_string = str_replace($replace, $replace_with, $string);
This should do it for you. http://www.php.net/manual/en/function.str-replace.php
Edited after you comments
Maybe it's not the best solution, but you can do it like this:
$string = 'text more text "empty space"';
preg_match('/(.*)(".*?")$/', $string, $matches);
$finaltext = $matches[1] . str_replace(' ', '###', $matches[2]);

PHP and regex Task

I have a string in php formatted like this:
http://aaaaaaaaaa/*http://bbbbbbbbbbbbbbb
where aaa... and bbb.... represent random characters and are random in length.
I would like to parse the string so that I am left with this:
http://bbbbbbbbbbbbbbb
In this case I wouldn't recommend regex but a simple substring or explode
$data = "http://aaaaaaaaaa/*http://bbbbbbbbbbb"
$parts = explode('*', $data);
echo $parts[1];
fin :)
You don't need regular expressions at all in this case:
$str = 'http://aaaaaaaaaa/*http://bbbbbbbbbbbbbbb';
echo substr($str, strpos($str, 'http://', 1));
Hi This would help you to get the address:
$str = 'http://www.example.com/*http://www.another.org/';
$pattern = '/^http:\/\/[\.\w\-]+\/\*(http:\/\/.+)$/';
//$result = preg_replace($pattern, '$1', $str);
$found = preg_match_all($pattern, $str, $result);
$url = (!$found==0) ? $result[1][0] : '';
echo $str . '<br />' . $url;
Here is the regular expression way:
$str = 'http://aaaaaaaaaa/*http://bbbbbbbbbbbbbbb';
$url = preg_replace("/^.*(http:\/\/.*[^(http:\/\/)+])$/", "$1", $str);
echo $url;
Here is a clean solution: grab everything after the last occurrence of "http://".
$start = strrpos($input, 'http://');
$output = substr($input, $start);

PHP sentence case function

I have got a function from Google to clean my paragraph in sentence case.
I want to modify this function such that it converts more than 2 new line character to newline. Else it converts all new line characters in space. So I would have it in paragraph format. Here it's converting all new line character to space.
It's converting in proper sentence case. But, In case If I found single word having first word as capital then I need function to ignore that. As Sometimes, if there would be any noun It needs to be capital. We can't change it small case. Else if noun and it is having more than 2 capital characters other than first character than convert it to lower case.
Like -> Noun => Noun but NoUn => noun. Means I want if other than first character is capital than it convert it two lower case Else it keep it in same format.
function sentence_case($string) {
$sentences = preg_split('/([.?!]+)/', $string, -1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
$new_string = '';
foreach ($sentences as $key => $sentence) {
$new_string .= ($key & 1) == 0?
ucfirst(strtolower(trim($sentence))) :
$sentence.' ';
}
$new_string = preg_replace("/\bi\b/", "I", $new_string);
//$new_string = preg_replace("/\bi\'\b/", "I'", $new_string);
$new_string = clean_spaces($new_string);
$new_string = m_r_e_s($new_string);
return trim($new_string);
}
function sentence_case($str) {
$cap = true;
$ret='';
for($x = 0; $x < strlen($str); $x++){
$letter = substr($str, $x, 1);
if($letter == "." || $letter == "!" || $letter == "?"){
$cap = true;
}elseif($letter != " " && $cap == true){
$letter = strtoupper($letter);
$cap = false;
}
$ret .= $letter;
}
return $ret;
}
This will preserve existing proper noun capitals, acronyms and abbreviations.
This should do it:
function sentence_case($string) {
// Protect the paragraphs and the caps
$parDelim = "/(\n+\r?)/";
$string = preg_replace($parDelim, "#PAR#", $string);
$string = preg_replace("/\b([A-Z])/", "#$1#", $string);
$sentences = preg_split('/([.?!]+)/', $string, -1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
$new_string = '';
foreach ($sentences as $key => $sentence) {
$new_string .= ($key & 1) == 0?
ucfirst(strtolower(trim($sentence))) :
$sentence.' ';
}
$new_string = preg_replace("/\bi\b/", "I", $new_string);
//$new_string = preg_replace("/\bi\'\b/", "I'", $new_string);
$new_string = clean_spaces($new_string);
$new_string = m_r_e_s($new_string);
// Restore the paragraphs and the caps
$new_string = preg_replace("#PAR#", PHP_EOL, $new_string);
$new_string = preg_replace("/#([A-Z])#/", "$1", $new_string);
return trim($new_string);
}
It works by identifying the items you want to protect (paragraph & first cap) and marking it with a string that you can then replace back when you are done. The assumption is that you don't already have #PAR# and #A-Z# in the string. You can use whatever you want to use for the paragraph delimiter afterwards if you want to force a certain type of line ending or several lines in between.
Slightly modifying Sylverdrag's function, I got something that is working well for me. This version works for every messed-up sentence I've thrown at it so far :)
function sentence_case($string) {
$string = strtolower($string); // ADDED THIS LINE
// Protect the paragraphs and the caps
$parDelim = "/(\n+\r?)/";
$string = preg_replace($parDelim, "#PAR#", $string);
$string = preg_replace("/\b([A-Z])/", "#$1#", $string);
$sentences = preg_split('/([.?!]+)/', $string, -1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
$new_string = '';
foreach ($sentences as $key => $sentence) {
$new_string .= ($key & 1) == 0?
ucfirst(strtolower(trim($sentence))) :
$sentence.' ';
}
$new_string = preg_replace("/\bi\b/", "I", $new_string);
// GOT RID OF THESE LINES
// $new_string = preg_replace("/\bi\'\b/", "I'", $new_string);
// $new_string = clean_spaces($new_string);
// $new_string = m_r_e_s($new_string);
// Restore the paragraphs and the caps
$new_string = preg_replace("#PAR#", PHP_EOL, $new_string);
$new_string = preg_replace("/#([A-Z])#/", "$1", $new_string);
$new_string = preg_replace("/#([A-Z])#/", "$1", $new_string);
preg_match('/#(.*?)#/', $new_string, $match); // MODIFIED THIS LINE TO USE (.*?)
return trim($new_string);
}
$string = "that IS it!! YOU and i are Totally DONE hanging out toGether... like FOREveR DUDE! i AM serious. a good FRIEND would NOT treAT me LIKE you dO. it Seems, howEVER, THAT you ARE not ONE of tHe GOOD ONEs.";
echo "<b>String 1:</b> " . $string . "<br><b>String 2:</b> " . sentence_case($string);
PHP Sandbox
:) :)

Categories