Actually this problem shouldn’t be that much hard but I searched for it in stackoverflow but couldn’t find anything that works as I want or I can understand. Here’s what i’m asking for:
Image there is a text like:
“hi today the temperature is high”
I’d like to replace string “hi” with “al” but I don’t want the word high to be replaced to as “algh”. I know I need to use preg_replace function but i couldn’t make it work.
ps: If you can show your solution with an array too, I will be more satisfied. Like there’s an array of strings to be changed and there’s an array of strings to be changed as.
Appreciate your help thanks :)
You can use regex with \b to make it work.
$string = 'hi today the temperature is high';
$pattern = '/\bhi\b/';
$replacement = 'al';
echo preg_replace($pattern, $replacement, $string);
\b assert position at a word boundary (^\w|\w$|\W\w|\w\W)
https://regex101.com/r/WdQTMp/2
I would recommend using a negative lookahead against the non-whitespace character \S.
This results in the simple regex hi(?!\S):
<?php
$string = "hi today the temperature is high";
$string2 = preg_replace('/hi(?!\S)/', 'al', $string);
echo $string2; // "al today the temperature is high";
This can be seen working here.
Note that this will only cover strings that start with hi. In order to exclude strings that have text before hi (like sushi), you'll need a negative lookbehind as well:
<?php
$string = "I eat sushi - hi today the temperature is high";
$string2 = preg_replace('/(?<!\S)hi(?!\S)/', 'al', $string);
echo $string2; // "I eat sushi - al today the temperature is high";
This can be seen working here.
Hope this helps! :)
For example:
<?php
$arrFrom = array("1","2","3","B");
$arrTo = array("A","B","C","D");
$word = "ZBB2";
echo str_replace($arrFrom, $arrTo, $word);
?>
I would expect as result: "ZDDB"
However, this return: "ZDDD"
(Because B = D according to our array)
To make this work, use "strtr" instead:
<?php
$arr = array("1" => "A","2" => "B","3" => "C","B" => "D");
$word = "ZBB2";
echo strtr($word,$arr);
?>
This returns: "ZDDB"
Related
i'm not very firm with regular Expressions, so i have to ask you:
How to find out with PHP if a string contains a word starting with # ??
e.g. i have a string like "This is for #codeworxx" ???
I'm so sorry, but i have NO starting point for that :(
Hope you can help.
Thanks,
Sascha
okay thanks for the results - but i did a mistake - how to implement in eregi_replace ???
$text = eregi_replace('/\B#[^\B]+/','\\1', $text);
does not work??!?
why? do i not have to enter the same expression as pattern?
Match anything with has some whitespace in front of a # followed by something else than whitespace:
$ cat 1812901.php
<?php
echo preg_match("/\B#[^\B]+/", "This should #match it");
echo preg_match("/\B#[^\B]+/", "This should not# match");
echo preg_match("/\B#[^\B]+/", "This should match nothing and return 0");
echo "\n";
?>
$ php 1812901.php
100
break your string up like this:
$string = 'simple sentence with five words';
$words = explode(' ', $string );
Then you can loop trough the array and check if the first character of each word equals "#":
if ($stringInTheArray[0] == "#")
Assuming you define a word a sequence of letters with no white spaces between them, then this should be a good starting point for you:
$subject = "This is for #codeworxx";
$pattern = '/\s*#(.+?)\s/';
preg_match($pattern, $subject, $matches);
print_r($matches);
Explanation:
\s*#(.+?)\s - look for anything starting with #, group all the following letters, numbers, and anything which is not a whitespace (space, tab, newline), till the closest whitespace.
See the output of the $matches array for accessing the inner groups and the regex results.
#OP, no need regex. Just PHP string methods
$mystr='This is for #codeworxx';
$str = explode(" ",$mystr);
foreach($str as $k=>$word){
if(substr($word,0,1)=="#"){
print $word;
}
}
Just incase this is helpful to someone in the future
/((?<!\S)#\w+(?!\S))/
This will match any word containing alphanumeric characters, starting with "#." It will not match words with "#" anywhere but the start of the word.
Matching cases:
#username
foo #username bar
foo #username1 bar #username2
Failing cases:
foo#username
#username$
##username
I have a string, for example
"The antelope is hungry today";
I want to search for "hungry" and replace whatever 3 characters are before it with "xxx" So the end result in this case would be
"The antelope xxxhungry today"
I thought maybe the substr_replace function might work, or maybe combining that with strlen, but I'm not getting it.
Thank you.
You can use strpos() and substr_replace() in combination to get your desired behavior:
$str = "The antelope is hungry today"; // str to search
$needle = "hungry"; // str to search for
// returns beginning index of 'hungry' (16 in this case)
$start_index = strpos($str, $needle);
$result = substr_replace($str, "xxx", ($start_index - 3), 3);
echo $result; // prints : The antelope xxxhungry today
See this phpfiddle for my working example.
you can use strpos() to find specific words inside strings
$value = "The antelope is hungry today";
if(strpos($value , 'hungry ') !== false){
echo "word found";
}
if you found the word you, then you can replace the words you like inside the if condition.
Your could use regular expressions
$pattern = "/.{3}(?=hungry)/";
$string = "The antelope is hungry today";
$replacement = "xxx";
echo preg_replace($pattern, $replacement, $string);
Explanation
. Match any character
{3} 3 times
(?=hungry) followed by hungry
try this function it will work finely and resolve your issue:
substr_replace($yourText,"XXX",(strpos($yourText,"partYouAreLookingFor")-3),3);
The function strpos enable to find the position of the text portion you are looking for. It will be used to define the starting point of the modifcation. the number 3 after represents the number of elements starting for the starting point that will be modified
I'm trying to replace 'he' by 'she' between two given positions, in this case between Maria(0) and Peter(34). So basically I give two positions and replace all the occurrences in the sentence between the boundaries. I have tried with the following simple code but it seems that the substr_replace function doesn't allow me to do it. Any idea to make it works?
$sentence = "Maria went to London where he met Peter with his family.";
$clean = substr_replace($sentence, "he", "she", 0, 34);
You are using substr_replace() incorrectly, and in this case you don't need it. Instead, try this, using a combo of str_replace() and substr():
$sentence = "Maria went to London where he met Peter with his family.";
$clean = str_replace(' he ', ' she ', substr($sentence, 0, 34));
$clean .= substr($sentence, 34);
See demo
Essentially, you are replacing he with she on the specified substr of $sentence, then concatenating the rest of $sentence back on.
Note the spaces around ' he ' and ' she '. This is necessary because otherwise you would replace where with wshere.
Edit: mark made me realized I misinterpretted your question. However I feel you might still find this regex useful, so I'm going to leave my answer but for the answer to your exact question look at MarkM's answer.
If you want to replace all instances of the word he with she only when the word 'he' occurs as its own word I would do something like this.
$pattern = '/(\b)he(\b)/';
$replacement = '$1she$2';
$subject = 'Maria went to London where he met Peter with his family';
$newString = preg_replace($pattern, $replacement, $subject);
The regex pattern basically says find all instances of the letters 'he' surrounded by valid word seperators (\b) and replace it with 'she' surrounded by the word separators that were found.
Edit:
See It Run
How can separate alphanumeric value with space in one statement
Example :
$arr="new stackoverflow 244code 7490script design";
So how can possible to separate alpha and number with space like :
$arr="new stackoverflow 244 code 7490 script design";
You can use preg_split() function
Check demo Codeviper
preg_split('#(?<=\d)(?=[a-z])#i', "new stackoverflow 244code 7490script design");
PHP
print_r(preg_split('#(?<=\d)(?=[a-z])#i', "new stackoverflow 244code 7490script design"));
Result
Array ( [0] => new stackoverflow 244 [1] => code 7490 [2] => script design )
You can also use preg_replace() function
Check demo Codeviper
PHP
echo preg_replace('#(?<=\d)(?=[a-z])#i', ' ', "new stackoverflow 244code 7490script design");
Result
new stackoverflow 244 code 7490 script design
Hope this help you!
You may use preg_replace (Example):
$arr = "new stackoverflow 244code 7490script design";
$newstr = preg_replace('#(?<=\d)(?=[a-z])#i', ' ', $arr);
echo $newstr; // new stackoverflow 244 code 7490 script design
The regex pattern used from user1153551's answer.
Use preg_replace like this:
$new = preg_replace('/(\d)([a-z])/i', "$1 $2", $arr);
regex101 demo
(\d) match and catches a digit. ([a-z]) matches and catches a letter. In the replace it puts back the digit, adds a space and puts back the letter.
If you don't want to use backreferences, you can use lookarounds:
$new = preg_replace('/(?<=\d)(?=[a-z])/i', ' ', $arr);
If you want to replace between letter and number as well...
$new = preg_replace('/(?<=\d)(?=[a-z])|(?<=[a-z])(?=\d)/i', ' ', $arr);
regex101 demo
(?<=\d) is a positive lookbehind that makes sure that there is a digit before the current position.
(?=[a-z]) is a positive lookahead that makes sure that there is a letter right after the current position.
Similarly, (?<=[a-z]) makes sure there's a letter before the current position and (?=\d) makes sure there's a digit right after the current position.
An different alternative would be to split and join back with spaces:
$new_arr = preg_split('/(?<=\d)(?=[a-z])/i', $arr);
$new = implode(' ', $new_arr);
Or...
$new = implode(' ', preg_split('/(?<=\d)(?=[a-z])/i', $arr));
preg_split
preg_split — Split string by a regular expression
<?php
// split the phrase by any number of commas or space characters,
// which include " ", \r, \t, \n and \f
$matches = preg_split('#(?<=\d)(?=[a-z])#i', "new stackoverflow 244code 7490script design");
echo $matches['0'],' '.$matches['1'].' '.$matches['2'];
?>
WORKING DEMO
I have a comment box on my site , what I want here is if a user writes input (any character) which is more than 20 characters and doesnot put space between them then it should place a space between it.
Like: "asdasdasdasdasdasdasdasd"
Parsed: "asdasdasdasdasdasdas dasd"
I think it can be done with string compare but I want the regex to match it or the full solution. Thanks for any help.
it is called word wrapping.
http://php.net/manual/en/function.wordwrap.php
from examples :
<?php
$text = "A very long woooooooooooord.";
$newtext = wordwrap($text, 8, " ", true);
echo "$newtext\n";
?>
output:
A very long wooooooo ooooord.
The function wordwrap does this job well. But here is a regex based solution:
$str = "asdasdasdasdasdasdasdasd";
$str = preg_replace('/(.{20})/','$1 ',$str);
This will put add a space even if the input is of size 20. If you don't want that use:
$str = preg_replace('/(.{20})(?=.)/','$1 ',$str);