Issue
I want to create a function to simplify names of companies (e.g., Apple Inc., Microsoft Corporation, Advanced Micro Devices, Inc.) and create a lowercase string to embed in a URL (e.g., apple, microsoft, advanced-micro-devices).
function cleanCompany($companyName){
$companyName= strtolower($companyName);
$companyName=preg_replace('/(!||&||,||\.||\'||\"||\(||\))/i', '', $companyName);
$companyName=str_replace(array('company',' corporation',', inc.',' inc.',' inc',' ltd.',' limited',' holding',' american depositary shares each representing one class a.',' american depositary shares each representing one class a',' american depositary shares each representing two',' american depositary shares each representing 2',' class a',' s.a.'), '', $companyName);
$companyName=preg_replace('/(\s+)/i', '-', $companyName);
return $companyName;
}
Company names are in this link: https://iextrading.com/trading/eligible-symbols/
This function still has problems that I am trying to solve it with:
$companyName=str_replace(array('---','--'), array('-'), $companyName);
How do I improve this function or do this task?
Solution
Based on Barmar's advice, I modified the function, which works okay.
function slugCompany($c){
$c= strtolower($c);
$c=preg_replace('/[^\da-z\s]/i', '', $c);
$c=str_replace(array('company',' corporation',', inc.',' inc.',' inc',' ltd.',' limited',' holding',' american depositary shares each representing one class a.',' american depositary shares each representing one class a',' american depositary shares each representing two',' american depositary shares each representing 2',' class a',' s.a.'), '', $c);
$c=preg_replace('/(\s+)/i', '-', $c);
return $c;
}
Also, I added a loop to replace '--'
to '-'
;
for ($i=0; $i < 5; $i++) {
if(strpos($c,'--')!==false){
$c=str_replace('--','-', $c);
}else{
break;
}
}
Another way, I tried
function slugCompany($c){
$c= strtolower($c);
$c=preg_replace('/[^\da-z\s]/i', '', $c);
$words='11000th|american|and|a|beneficial|bond|b|class|common|company|corporation|corp|commodity|cumulative|co|c|daily|dep|depositary|depository|debentures|diversified|due|d|each|etf|equal|equity|exchange|e|financial|fund|fixedtofloating|fixed|floating|f|group|g|healthcare|holdings|holding|h|inc|incorporated|interests|interest|in|index|income|i|junior|j|k|liability|limited|lp|llc|ltd|long|l|markets|maturity|municipal|muni|monthly|m|noncumulative|notes|no|n|of|one|or|o|portfolio|pay|partnership|partner|par|perpetual|per|perp|pfd|preference|preferred|p|q|redeemable|repstg|representing|represents|rate|r|sa|smallcap|series|shs|shares|share|short|stock|subordinated|ser|senior|s|the|three|term|to|traded|trust|two|t|ultrashort|ultra|u|value|v|warrant|weight|w|x|y|z';
$c=preg_replace('/\b('.$words.')\b/i', '', $c);
$c=preg_replace('/(\s+)/i', '-', trim($c));
return $c;
}
Answered By - Emma Answer Checked By - Robin (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.