Replace empty spaces with ### from Text between " " in a string in PHP - 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]);

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;

PHP: remove word from sentence if it contains #

I want to remove words from sentence if word contains #, I am using php.
Input: Hi I am #RaghavSoni
Output: Hi I am
Thank You.
You could do:
$str = preg_replace('/#\w+/', '', $str);
This is not a good way, but it works :
<?php
$input="Hi I am #RaghavSoni";
$inputWords = explode(' ', $input);
foreach($inputWords as $el)
{
if($el[0]=="#" )
{
$input = str_replace($el, "", $input);
}
}
echo $input;
?>
while(strpos($string, '#') !== false) {
$location1 = strpos($string, "#");
$location2 = strpos($string, " ", $location1);
if($location2 !== false) {
$length = $location2 - $location1;
$string1 = substr($string, 0, $location1);
$string2 = substr($string, $location2);
$string = $string1 . $string2;
}
}
echo $string;
echo str_replace("#RaghavSoni", "", "Hi I am #RaghavSoni.");
# Output: Hi I am.

Propper Regex Pattern

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

PHP : How To Get 'Unmatch' String?

I have this array :
$GivenString = array("world", "earth", "extraordinary world");
how to get 'unmatch' string of variables like this :
$string = 'hello, world'; // output = 'hello, '
$string = 'down to earth'; // output = 'down to '
$string = 'earthquake'; // output = ''
$string = 'perfect world'; // output = 'perfect '
$string = 'I love this extraordinary world'; // output = 'I love this '
thanks!
I think simple str_replace will help you
$GivenString = array("world", "earth", "extraordinary");
echo str_replace($GivenString, "", $string);
array_diff http://php.net/manual/en/function.array-diff.php
$tokens = explode(' ', $string);
$difference = array_diff($tokens, $GivenString);
str_replace will not help, as there are $string = 'earthquake'; // output = '' in example. Here's piece of code that will do your job done.
$GivenString = array("world", "earth", "extraordinary world");
foreach ($GivenString as &$string) {
$string = sprintf('%s%s%s', '[^\s]*', preg_quote($string, '/'), '[^\s]*(\s|)');
}
// case sensitive
$regexp = '/(' . implode('|', $GivenString) . ')/';
// case insensitive
// $regexp = '/(' . implode('|', $GivenString) . ')/i';
$string = 'earthquake';
echo preg_replace($regexp, '', $string);

Categories