PHP汉字转拼音带声调
不使用第三方库
话不多说,直接上代码
实现思路就是用curl获取远程地址带拼音的内容,然后使用正则匹配出拼音即可
public function getWordsGroupInfo($content){
$wordGroupInfo = array();
$param = array(
'wd' => $content
);
// 这里使用 CURL 进行请求
$web = Ap_Util_Http::get("https://hanyu.baidu.com/zici/s",$param);
if(mb_strlen($content) > 1){
preg_match_all('/<div id="pinyin".*>.*<b>(.*)<\/b>.*<\/div>/isU', $web, $pinyin);
if(isset($pinyin[1][0])){
$wordGroupInfo['pinyin'] = trim(trim($pinyin[1][0],'[]'));
}else{
$wordGroupInfo['pinyin'] = "";
}
}else{
preg_match_all('/<div class="pronounce" id="pinyin".*>.*<b>(.*)<\/b>.*<\/div>/isU', $web, $pinyin);
if(isset($pinyin[1][0])){
$wordGroupInfo['pinyin'] = $pinyin[1][0];
}else{
$wordGroupInfo['pinyin'] = "";
}
}
return $wordGroupInfo;
}