Can someone tell me please how to do this:
Input:
hello http://DOMAIN.com/asdakdjk.php?asd=231&adsj=23 u.s. nicely done!
Result:
Hello http://DOMAIN.com/asdakdjk.php?asd=231&adsj=23 U.S. Nicely Done!
Including words in separated by '.' if possible such as in U.S.
Thanks
try this:
<?php
function capitalizeNonURLs($input)
{
preg_match('#(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)#', $input, $matches);
$url = $matches[1];
$temp = ucwords($input);
$output = str_ireplace($url, $url, $temp);
return $output;
}
$str = "hello http://domain.com/asdakdjk.php?asd=231&adsj=23 u.s. nicely done!";
echo capitalizeNonURLs($str);
Keep in mind that this function does not handle abbreviations (it won't change usa to USA). Country codes can be handled in several different ways. One is to make a hashmap of country codes and replace them or use regular expression for that as well.
To keep urls lower:
$strarray = explode(' ',$str);
for($i=0;$i<count($strarray))
{
if(substr($strarray[$i],0,4)!='http')
{
$strarray[$i] = ucfirst($strarray[$i])
}
}
$new_str = implode('',$strarray);
Related
I'm developing an application that takes a full name of a person and then processes it. For example, if the user enters the name like this:
"AlanMichel"
Then the result must be:
"Alan Michel"
I didn't know how I can do that in the php. Anyone can help please?
You can do:
$str = "AlanMichel";
$name = preg_split('/(?=[A-Z])/',$str);
echo implode( " ", $name );
This will result to:
Alan Michel
Try this
function splitAtUpperCase($s) {
return preg_split('/(?=[A-Z])/', $s, -1, PREG_SPLIT_NO_EMPTY);
}
$str = "AlanMichel";
$strArray = splitAtUpperCase($str));
echo $strArray[0]; //first name
echo $strArray[1]; //second name
Output
Alan
Michel
If you don't need the array itself, you can just preprend uppercase characters (except the first) with a space
echo preg_replace('/(?<!^)([A-Z])/', ' \\1', $str);
I want to make some changes to the html but I have to follow certain rules.
I have a source code like this;
A beautiful sentence http://www.google.com/test, You can reach here http://www.google.com/test-mi or http://www.google.com/test/aliveli
I need to convert this into the following;
A beautiful sentence http://test.google.com/, You can reach here http://www.google.com/test-mi or http://test.google.com/aliveli
I tried using str_replace;
$html = str_replace('://www.google.com/test','://test.google.com');
When I use it like this, I get an incorrect result like;
A beautiful sentence http://test.google.com/, You can reach here http://test.google.com/-mi or http://test.google.com/aliveli
Wrong replace: http://test.google.com/-mi
How can I do this with preg_replace?
With regex you can use a word boundary and a lookahead to prevent replacing at -
$pattern = '~://www\.google\.com/test\b(?!-)~';
$html = preg_replace($pattern, "://test.google.com", $html);
Here is a regex demo at regex101 and a php demo at eval.in
Be aware, that you need to escape certain characters by a backslash from it's special meaning to match them literally when using regex.
It seems you're replacing the subdirectory test to subdomain. Your case seems to be too complicated. But I've given my best to apply some logic which may be reliable or may not be unless your string stays with the same structure. But you can give a try with this code:
$html = "A beautiful sentence http://www.google.com/test, You can reach here http://www.google.com/test-mi or http://www.google.com/test/aliveli";
function set_subdomain_string($html, $subdomain_word) {
$html = explode(' ', $html);
foreach($html as &$value) {
$parse_html = parse_url($value);
if(count($parse_html) > 1) {
$path = preg_replace('/[^0-9a-zA-Z\/-_]/', '', $parse_html['path']);
preg_match('/[^0-9a-zA-Z\/-_]/', $parse_html['path'], $match);
if(preg_match_all('/(test$|test\/)/', $path)) {
$path = preg_replace('/(test$|test\/)/', '', $path);
$host = preg_replace('/www/', 'test', $parse_html['host']);
$parse_html['host'] = $host;
if(!empty($match)) {
$parse_html['path'] = $path . $match[0];
} else {
$parse_html['path'] = $path;
}
unset($parse_html['scheme']);
$url_string = "http://" . implode('', $parse_html);
$value = $url_string;
}
}
unset($value);
}
$html = implode(' ', $html);
return $html;
}
echo "<p>{$html}</p>";
$modified_html = set_subdomain_string($html, 'test');
echo "<p>{$modified_html}</p>";
Hope it helps.
If the sentence is the only case in your problem you don't need to start struggling with preg_replace.
Just change your str_replace() functioin call to the following(with the ',' at the end of search string section):
$html = str_replace('://www.google.com/test,','://test.google.com/,');
This matches the first occurance of desired search parameter, and for the last one in your target sentence, add this(Note the '/' at the end):
$html = str_replace('://www.google.com/test/','://test.google.com/');
update:
Use these two:
$targetStr = preg_replace("/:\/\/www.google.com\/test[\s\/]/", "://test.google.com/", $targetStr);
It will match against all but the ones with comma at the end. For those, use you sould use the following:
$targetStr = preg_replace("/:\/\/www.google.com\/test,/", "://test.google.com/,", $targetStr);
I wan't to create a highlight tag search function via php
when I search a part of word...whole of word be colored
for example this is a sample text:
Text: British regulators say traders used private online chatrooms to coordinate their buying and selling to shift currency prices in their favor.
when I search "th" the output be like this:
Text: British regulators say traders used private online chatrooms to coordinate their buying and selling to shift currency prices in their favor.
So...I tried this code...please help me to complete it.
This is a algorithm:
$text= "British regulators say...";
foreach($word in $text)
{
if( IS There "th" in $word)
{
$word2= '<b>'.$word.'</b>'
replace($word with word2 and save in $text)
}
}
how can I it in php language?
function highLightWords($string,$find)
{
return preg_replace('/\b('.$find.'\w+)\b/', "<b>$1</b>", $string);
}
Usage:
$string="British regulators say traders used private online chatrooms to coordinate their buying and selling to shift currency prices in their favor.";
$find="th";
print_r(highLightWords($string,$find));
Fiddle
Edit after your comment:
...How can I do it for middle characters? for example "line"
Very easy, just update the regex pattern accordingly
return preg_replace("/\b(\w*$find\w*)\b/", "<b>$1</b>", $string);
Fiddle
Use strpos() to find the position of the character you search for.. Then start reading from that identified position of character to till you don't find any space..
Should be much easier:
$word = "th";
$text = preg_replace("/\b($word.*?)\b/", "<b>$1</b>", $text);
Let's say a lot of things.
First, as you know php is a server-side code, so, as long as you won't mind reload the page each time or use ajax...
The correct way i think will be using Javascript to Achieve this.
That said to explode the text you need to use another function, to be sure of what obtained:
Something like:
$str = "Hello world. It's a beautiful day.";
$words = explode(" ",$str);
Now Words var will contain the exploded string.
Now you can loop and replace (for example) and then re-construct the string and print it or do other.
You can go with the following code
<?php
$string = "British regulators say traders used private online chatrooms to coordinate their buying and selling to shift currency prices in their favor";
$keyword = "th";
echo highlightkeyword($string , $keyword );
function highlightkeyword($str, $search) {
$occurrences = substr_count(strtolower($str), strtolower($search));
$newstring = $str;
$match = array();
for ($i=1;$i<$occurrences;$i++) {
$match[$i] = stripos($str, $search, $i);
$match[$i] = substr($str, $match[$i], strlen($search));
$newstring = str_replace($match[$i], '[#]'.$match[$i].'[#]', strip_tags($newstring));
}
$newstring = str_replace('[#]', '<b>', $newstring);
$newstring = str_replace('[#]', '</b>', $newstring);
return $newstring;
}
?>
Check here https://eval.in/220395
I hate this code. What it does is take zipcode from html pages are verifies if the zipcode is USA or Canada.
<?php
$contents = file_get_contents('853755.html');
preg_match_all('/<td id="u_zipCode">(.*?)<\/td>/s', $contents, $matches);
$data = implode("|",$matches[0]);
$string = str_replace(' ', '', $data);
if(preg_match('/^[1-9][0-9]*$/',$string)){
echo "Canada";
}
else
{
echo "USA";
}
?>
I tried very had to search solution for it. But i can't find the solution. I even tried the regex that it should only contain Numbers not a single alphabet. But this doesn't seem to work in any way. The zipcode are given in this format,
USA: 97365
USA: 97365-97366
Canada: j8n7s1
Canada: N2L5Y6
Kindly help me with this solution. Thanks
Since there can only be one element with a particular ID, you don't need to use preg_match_all(), you can use preg_match().
preg_match('/<td id="u_zipCode">(.*?)<\/td>/s', $contents, $match);
Then you don't need to use implode(). The part that matches the capture group will be in element 1 of the match array.
$string = str_replace(' ', '', $match[1]);
if(preg_match('/^\d{5}(-\d{4})?$/',$string)) {
echo "USA";
} else {
echo "Canada";
}
I'm sure someone already asked this question, but after searching for more than 1 hour on google, I decided to ask my question here.
I want to itterate over an array excisting of different strings/texts.
These texts contain strings with both ##valuetoreplace## and #valuetoreplace#
I want to make to preg_matches:
$pattern = '/^#{1}+(\w+)+#{1}$/';
if(preg_match($pattern, $value, $matches, PREG_OFFSET_CAPTURE))
{
// do something with the #values#
}
AND
$pattern = '/^#{2}+(\w+)+#{2}$/';
if(preg_match($pattern, $value, $matches, PREG_OFFSET_CAPTURE))
{
//do something with the ##value##
}
This works great.
Now my only problem is as follows:
When i have a string like
$valueToMatch = 'proceding text #value#';
My preg_match cant find my value anymore (as i used a ^ and a $).
Question: how can i find the #value# and the ##value##, without having to worry if these words are in the middle of a (multi-line) value?
*In addition:
What i want is to find patterns and replace the #value# with a db value and a ##value## with a array value.
For example:
$thingsToReplace = 'Hello #firstname# #lastname#,
How nice you joined ##namewebsite##.';
should be
'Hello John Doe,
How nice you joined example.com.'
Try this: /##([^#]+)##/ and /#([^#]+)#/, in that order.
Maybe nice to know for other visitors how i did it:
foreach($personalizeThis as $key => $value)
{
//Replace ##values##
$patternIniData = '/#{2}+(\w+)#{2}/';
$return = 'website'; //testdata
$replacedIniData[$key] = preg_replace($patternIniData, $return, $value);
//Replace #values#
$pattern = '/#{1}+(\w+)#{1}/';
$return = 'ASD'; //testdata
$replacedDbData[$key] = preg_replace($pattern, $return, $replacedIniData[$key]);
}
return $replacedDbData;