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);
Related
i need some help. how to count the length of each word in the text file using PHP.
for example. there is the test.txt. and the contain is " hello everyone, i need some help."
how to output the text and then count the length of each word,like:
array
hello => 5
everyone => 8
i => 1
need => 4
some => 4
help => 4
i just start to learn php. so please explain the detail about the code what you write.
many thanks
This should work
$text = file_get_contents('text.txt'); // $text = 'hello everyone, i need some help.';
$words = str_word_count($text, 1);
$wordsLength = array_map(
function($word) { return mb_strlen($word, 'UTF-8'); },
$words
);
var_dump(array_combine($words, $wordsLength));
For more informations about str_word_count and its parameters see http://php.net/manual/en/function.str-word-count.php
Basically, everything is well described on php.net. The function array_map walks through given array and applies given (eg. anonymous) function on every item in that array. The function array_combine creates an array by using one array for keys and another for its values.
this is working
$stringFind="hello everyone, i need some help";
$file=file_get_contents("content.txt");/*put your file path */
$isPresent=strpos($file,$stringFind);
if($isPresent==true){
$countWord=explode(" ",$stringFind);
foreach($countWord as $val){
echo $val ." => ".strlen($val)."<br />";
}
}else{
echo "Not Found";
}
If you don't need to process the words' length later, try this:
// Get file contents
$text = file_get_contents('path/to/file.txt');
// break text to array of words
$words = str_word_count($text, 1);
// display text
echo $text, '<br><br>';
// and every word with it's length
foreach ($words as $word) {
echo $word, ' => ', mb_strlen($word), '<br>';
}
But be noticed, that str_word_count() function has many issues with UTF-8 string (f.e. Polish, Czech and similar characters). If you need those, then I suggest filtering out commas, dots and other non-word characters and using explode() to get $words array.
I have some problems with the preg_replace.
I would change the mentions in a links but the name isn't a username.
So in the name there are spaces, i found a good solution but i don't know to do it.
Sostantially i would that preg_replace the words that are between # and ,
For example:
#John Doeh, #Jenna Diamond, #Sir Duck Norman
and replace to
VAL
How do I do it?
I think that you want it like:
John Doeh
For this try:
$myString="#John Doeh, #Jenna Diamond, #Sir Duck Norman";
foreach(explode(',',$myString) as $str)
{
if (preg_match("/\\s/", $str)) {
$val=str_replace("#","",trim($str));
echo "<a href='user.php?name=".$val."'>".$val."</a>";
// there are spaces
}
}
Based on my assumption you want to remove strings which start with #Some Name, in a text like: #Some Name, this is a message.
Then replace that to an href, like: First_Name
If that is the case then the following regex will do:
$str = '#First_Name, say something';
echo preg_replace ( '/#([[:alnum:]\-_ ]+),.*/', '$1', $str );
Will output:
First_Name
I also added support for numbers, underscores and dashes. Are those valid in a name aswell? Any other characters that are valid in a #User Name? Those are things that are important to know.
Two methods:
<?php
// preg_replace method
$string = '#John Doeh, #Jenna Diamond, #Sir Duck Norman';
$result = preg_replace('/#([\w\s]+),?/', '$1', $string);
echo $result . "<br>\n";
// explode method
$arr = explode(',', $string);
$result2 = '';
foreach($arr as $name){
$name = trim($name, '# ');
$result2 .= ''.$name.' ';
}
echo $result2;
?>
I am writing a program in PHP, and i need to find data that is in between two sets of symbols, and convert that to a string. For example
$main = "Hello, everyone, my name is (-Jack-)"
$string = regex_function('(-', $main) #should return "Jack"
How do i get that output, using a regex function or something
Try this :
$main = 'Hello, everyone, my name is (-Jack-)';
preg_match_all('/\(\-(?P<name>.*)\-\)/', $main, $matches);
echo "<pre>";
print_r($matches);
echo $matches['name'][0];
The function is known as preg_match_all().
$main = "Hello, everyone, my name is (-Jack-)";
preg_match_all('/\(\-(?P<name>\w+)\-\)/', $main, $string);
print_r( $string );
A sample output on codepad.
Referring to #Prasanth's comment; here's a better regex.
$main = "Hello, everyone, my name is (-Jack stuff-) some more text (-John stuff-)";
preg_match_all('/\(\-(?P<name>[\s\w]+)\-\)/', $main, $string);
print_r( $string );
Codepad link.
I have a small problem. I am tryng to convert a string like "1 234" to a number:1234
I cant't get there. The string is scraped fro a website. It is possible not to be a space there? Because I've tried methods like str_replace and preg_split for space and nothing. Also (int)$abc takes only the first digit(1).
If anyone has an ideea, I'd be greatefull! Thank you!
This is how I would handle it...
<?php
$string = "Here! is some text, and numbers 12 345, and symbols !£$%^&";
$new_string = preg_replace("/[^0-9]/", "", $string);
echo $new_string // Returns 12345
?>
intval(preg_replace('/[^0-9]/', '', $input))
Scraping websites always requires specific code, you know how you receive the input - and you write code that is required to make it usable.
That is why first answer is still str_replace.
$iInt = (int)str_replace(array(" ", ".", ","), "", $iInt);
$str = "1 234";
$int = intval(str_replace(' ', '', $str)); //1234
I've just came into the same issue, however the answer that was provided wasn't covering all the different cases I had...
So I made this function (the idea popped in my mind thanks to Dan) :
function customCastStringToNumber($stringContainingNumbers, $decimalSeparator = ".", $thousandsSeparator = " "){
$numericValues = $matches = $result = array();
$regExp = null;
$decimalSeparator = preg_quote($decimalSeparator);
$regExp = "/[^0-9$decimalSeparator]/";
preg_match_all("/[0-9]([0-9$thousandsSeparator]*)[0-9]($decimalSeparator)?([0-9]*)/", $stringContainingNumbers, $matches);
if(!empty($matches))
$matches = $matches[0];
foreach($matches as $match):
$numericValues[] = (float)str_replace(",", ".", preg_replace($regExp, "", $match));
endforeach;
$result = $numericValues;
if(count($numericValues) === 1)
$result = $numericValues[0];
return $result;
}
So, basically, this function extracts all the numbers contained inside of a string, no matter how many text there is, identifies the decimal separator and returns every extracted number as a float.
One can specify what decimal separator is used in one's country with the $decimalSeparator parameter.
Use this code for removing any other characters like .,:"'\/, !##$%^&*(), a-z, A-Z :
$string = "This string involves numbers like 12 3435 and 12.356 and other symbols like !## then the output will be just an integer number!";
$output = intval(preg_replace('/[^0-9]/', '', $string));
var_dump($output);
Example Input: SMK SUNGAI PUNAI
My Code:
$school = 'SMK SUNGAI PUNAI';
echo ucwords(strtolower($school));
Unwanted Output: Smk Sungai Punai
Question
How to make the output SMK Sungai Punai which allows SMK to remain in ALL-CAPS.
Update.
The problem I have list of 10,000 school names. From PDF, I convert to mysql. I copied exactly from PDF the name of schools -- all in uppercase.
How can I implement conditional title-casing?
As far as I understand you want to have all school names with the first character of every word in uppercase and exclude some special words ($exceptions in my sample) from this processing.
You could do that like this:
function createSchoolName($school) {
$exceptions = array('SMK', 'PTS', 'SBP');
$result = "";
$words = explode(" ", $school);
foreach ($words as $word) {
if (in_array($word, $exceptions))
$result .= " ".$word;
else
$result .= " ".strtolower($word);
}
return trim(ucwords($result));
}
echo createSchoolName('SMK SUNGAI PUNAI');
This example would return SMK Sungai Punai as required by your question.
You can very simply create a pipe-delimited set of excluded words/acronyms, then use (*SKIP)(*FAIL) to prevent matching those whole words.
mb_convert_case() is an excellent function to call because it instantly provides TitleCasing and it is multibyte safe.
Code: (Demo)
$pipedExclusions = 'SMK|USA|AUS';
echo preg_replace_callback(
'~\b(?:(?:' . $pipedExclusions . ')(*SKIP)(*FAIL)|\p{Lu}+)\b~u',
fn($m) => mb_convert_case($m[0], MB_CASE_TITLE),
'SMK SUNGAI PUNAI'
);
// SMK Sungai Punai
There's no really good way to do it. In this case you can assume it's an abbreviation because it's only three letters long and contains no vowels. You can write a set of rules that look for abbreviations in the string and then uppercase them, but in some cases it'll be impossible... consider "BOB PLAYS TOO MUCH WOW."
You can use something like this:
<?php
$str = 'SMK SUNGAI PUNAI';
$str = strtolower($str);
$arr = explode(" ", $str);
$new_str = strtoupper($arr[0]). ' ' .ucfirst($arr[1]). ' ' .ucfirst($arr[2]);
echo '<p>'.$new_str.'</p>';
// Result: SMK Sungai Punai
?>