$string = 'I am chan, my son is chan_junior';
$search = array('chan', 'chan_junior');
$replace = array('a', 'b');
$new = str_replace($search, $replace, $string);
echo $new;
I want to replace the string to I am a, my son is b, but the result is I am a, my son is a_junior. Is there a function to make it happen?
That happens because php search first for "chan", replace it on 2 places and then don't find second string. Search for longer strings first.
This works:
$string = 'I am chan, my son is chan_junior';
$search = array('chan', 'chan_junior');
$replace = array('a', 'b');
$str_arr = explode(' ', $string);
$count = count($str_arr);
for ($i = 0; $i < $count; $i ++)
{
$word = preg_replace('/^[^A-Za-z0-9\-]*|[^A-Za-z0-9\-]*$/', '', $str_arr[$i]);
if (in_array($word, $search))
{
$key = array_search($word, $search);
$str_arr[$i] = str_replace($word, $replace[$key], $str_arr[$i]);
}
}
$new = implode(' ', $str_arr);
echo $new;
Related
My code so far:
$text = 'Herman Archer LIVEs in neW YORK';
$oldWords = explode(' ', $text);
$newWords = array();
$counter = 0;
foreach ($oldWords as $word) {
for($k=0;$k<strlen($word);$k++)
$counter = 0;
if ($word[k] == strtoupper($word[$k]))
$counter=$counter+1;
if($counter>1)
$word = strtolower($word);
if($counter == 1)
$word = ucfirst(strtolower($word));
else $word = strtolower($word);
echo $word."<br>";
}
Result:
Herman
Archer
Lives
In
New
York
Expected output:
Herman Archer lives in new york
If you want to use the counter approach you could use something as the following
<?php
$text = 'Herman Archer LIVEs in A neW YORK';
$words = explode(' ', $text);
foreach($words as &$word) {
$counter = 0;
for($i = 1; $i <= strlen($word);$i++) {
if (strtoupper($word[$i]) == $word[$i]) $counter++;
if ($counter == 2) break;
}
if ($counter == 2) $word = strtolower($word);
}
echo implode(' ', $words);
Let's do it in a simple manner. Let's loop $oldWords, compare the strings from the second character to the end with their lower-case version and replace if the result is different.
for ($index = 0; $index < count($oldWords); $index++) {
//Skip one-lettered words, such as a or A
if (strlen($oldWords[$index]) > 1) {
$lower = strtolower($oldWords[$index]);
if (substr($oldWords[$index], 1) !== substr($lower, 1)) {
$oldWords[$index] = $lower;
}
}
}
If you are using not only English language, you might want to switch to mb_strtolower
<?php
$text = 'Herman Archer LIVEs in neW YORK';
function normalizeText($text)
{
$words = explode(" ", $text);
$normalizedWords = array_map(function ($word) {
$loweredWord = strtolower($word);
if (ucfirst($loweredWord) === $word) {
return $word;
}
return $loweredWord;
}, $words);
return join(" ", $normalizedWords);
}
echo normalizeText($text) . PHP_EOL; // Herman Archer lives in new york
you can combine ctype_upper for first character and ctype_lower for the rest
$text = 'Herman Archer LIVEs in neW YORK';
$oldWords = explode(' ', $text);
$newWords = '';
foreach ($oldWords as $word) {
if(ctype_upper($word[0])&&ctype_lower(substr($word,1))){
$newWords .= $word.' ';
}else{
$newWords .= strtolower($word).' ';
}
}
echo $newWords;
Meanwhile I've found out that this can be done in an easier way
if(isset($_POST["sumbit"])){
$string = $_POST["string"];
if(!empty($string)){
$word = explode (" ",$string);
foreach($words as $word){
//cut the first letter.
//check caselower.
//if not, attach the letter back and turn all lowercase.
//if yes, attach the letter back and leave it .
$wordCut = substr($word,1);
if(ctype_lower($wordCut)){
echo $word." ";
} else {
echo strtolower($word). " ";
}
}
I have the following code:
$caption = $picture->getCaption();
$words = explode(" ", $caption);
foreach ($words as $word) {
$string_length = strlen($word);
if ($string_length > 40) {
str_replace($word, '', $caption);
$picture->setCaption($caption);
}
}
However, why doesn't this replace the caption with the trimmed word removed?
You need to do like this:
$caption = $picture->getCaption();
$words = explode(" ", $caption);
foreach ($words as $word)
{
$string_length = strlen($word);
if ($string_length > 40) {
$picture->setCaption(str_replace($word, '', $caption));
}
}
You need to assign the replacement made:
$caption = str_replace($word, '', $caption);
I think this is much better:
$caption = $picture->getCaption();
// explode them by spaces, filter it out
// get all elements thats just inside 40 char limit
// them put them back together again with implode
$caption = implode(' ', array_filter(explode(' ', $caption), function($piece){
return mb_strlen($piece) <= 40;
}));
$picture->setCaption($caption);
You have to do it like that :
$caption = $picture->getCaption();
$words = explode(" ", $caption);
foreach ($words as $word)
{
$string_length = strlen($word);
if ($string_length > 40) {
$replaced = str_replace($word, '', $caption);
$picture->setCaption($replaced);
}
}
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;
$title = '228-example-of-the-title'
I need to convert the string to:
Example Of The Title
How would I do that?
A one-liner,
$title = '228-example-of-the-title';
ucwords(implode(' ', array_slice(explode('-', $title), 1)));
This splits the string on dashes (explode(token, input)),
minus the first element (array_slice(array, offset))
joins the resulting set back up with spaces (implode(glue, array)),
and finally capitalises each word (thanks salathe).
$title = '228-example-of-the-title'
$start_pos = strpos($title, '-');
$friendly_title = str_replace('-', ' ', substr($title, $start_pos + 1));
You can do this using the following code
$title = '228-example-of-the-title';
$parts = explode('-',$title);
array_shift($parts);
$title = implode(' ',$parts);
functions used: explode implode and array_shift
$pieces = explode("-", $title);
$result = "";
for ($i = 1; $i < count(pieces); $i++) {
$result = $result . ucFirst($pieces[$i]);
}
$toArray = explode("-",$title);
$cleanArray = array_shift($toArray);
$finalString = implode(' ' , $cleanArray);
// echo ucwords($finalStirng);
Use explode() to split the "-" and put the string in an array
$title_array = explode("-",$title);
$new_string = "";
for($i=1; $i<count($title_array); $i++)
{
$new_string .= $title_array[$i]." ";
}
echo $new_string;
Could anyone please help me with the regex of reversing each word in a string?
Sample input:
Hello how are you my friend?
Desired Output
olleH woh era uoy ym ?dneirf
I want to implement this in PHP.
This gives you almost what you want.
If it isn't close enough, look into Blender's solution of exploding on spaces.
preg_replace_callback('/\b(\w+)\b/', function($match) {
return strrev($match[1]);
}, $str);
CodePad.
You can reverse text using plain regex (and some string functions) but it is ugly...
$length = strlen($str);
echo preg_replace(
'/' . str_repeat('(.)', $length) . '/s',
'$' . join('$', range($length, 1)),
$str
);
CodePad.
The code sample above is for demonstration only. Please do not ever use it :)
That can't be done in pure regex, sorry.
Here's a possibly-working PHP script:
$exploded = explode(' ', $string);
$temp = array();
for ($i = 0; $i < count(exploded); $i++) {
$temp[] = strrev(exploded[i]);
}
$temp = implode(' ', $temp);
Not Regex, but this works:
<?php
function reverseWords($text) {
$words = explode(' ', $text);
$c_words = count($words);
$outtext = "";
for ($i = 0; $i < $c_words; $i++) {
if ($i !== 0) $outtext .= " ";
$length = strlen($words[$i]);
for ($p = $length-1; $p >= 0; $p--) {
$outtext .= substr($words[$i], $p, 1);
$start--;
}
}
return $outtext;
}
echo reverseWords("This is a test.");
?>
https://ideone.com/WUtzJ
Now, I forgot about strrev(), so that would shorten it a bit.
EDIT
Using strrev():
<?php
function reverseWords($text) {
$words = explode(' ', $text);
$c_words = count($words);
$outtext = "";
for ($i = 0; $i < $c_words; $i++) {
if ($i !== 0) $outtext .= " ";
$outtext .= strrev($words[$i]);
}
return $outtext;
}
echo reverseWords("This is a test.");
?>
https://ideone.com/NT7A5
This is extremely trivial to accomplish without a regular expression, and I see a lot of massive solutions here, so I thought I'd post a one-liner:
$rev = implode(' ', array_map('strrev', explode(' ', $string)));