0
我有一個PHP類,突出顯示文本中提到的名稱鏈接。它可以搜索給定文本中的@character並檢查名稱跟隨那個角色。從php類中的函數返回一個變量(返回不工作只回聲作品)
問題是,當我負責處理文本的方法(public function process_text ($text_txt){}
)時,類的返回值沒有打印出來。但是,當我將return
語言結構更改爲print
或echo
時,解析是成功的,並且打印出處理的字符串。我需要return
而不是print
,以便能夠將返回字符串存儲在我的CMS的評論表中。
請參閱完整的代碼如下,並建議:
class mentions {
public $print_content = '';
private $m_names = array();
private $m_denied_chars = array(
"@",
"#",
"?",
"¿"
);
private $m_link = "http://example.com/"; // + name of the username, link or whatever
/*
* this class can also be used for specific links
* start editing from here
* */
public function add_name ($name) {
array_push($this->m_names, $name);
}
public function process_text ($text_txt) {
$expl_text = explode(" ", $text_txt);
/*
* a character will be ignores which can be specified next this comment
* :)
* */
$sp_sign = "@"; // this is what you can change freely...
for ($i = 0; $i < count($expl_text); ++$i) {
$spec_w = $expl_text[$i];
$print_link = false;
$name_link = "";
if ($spec_w[0] == $sp_sign) { // then can be a mention...
$name = "";
$break_b = false;
for ($x = 1; $x < strlen($spec_w); ++$x) {
if ($spec_w[$x] == '.' || $spec_w[$x] == ",") {
if (in_array($name, $this->m_names)) {
$print_link = true;
$name_link = $name;
break;
}
}
if (in_array($spec_w[$x], $this->m_denied_chars)) {
$break_b = true;
break;
}
$name .= $spec_w[$x];
}
if ($break_b == true) {
$print_link = false;
break;
} else {
if (in_array($name, $this->m_names)) {
$print_link = true;
$name_link = $name;
}
}
}
if ($print_link == true) {
$this->print_content = "<a href=\"".$this->m_link."".$name_link."\">".$spec_w."</a>";
if ($i < count($expl_text)) $this->print_content .= " ";
} else {
$this->print_content = $spec_w;
if ($i < count($expl_text)) $this->print_content .= " ";
}
return $this->print_content;
}
}
}
###### create new class object and process raw data ######
$mentions = new mentions;
$raw_data = 'Hello, @Angelina. I am @Bob_Marley.';
$expr = '#(?:^|\W)@([\w-]+)#i';
preg_match_all($expr, $raw_data, $results);
if(!empty($results[1])) {
foreach($results[1] as $user) {
$mentions->add_name($user);
}
/*
------------------------------------
*/
$commenData = $mentions->process_text($raw_data);
echo $commenData;
}
可以嗎? var_dump'$ mentions'變量? –
你可以發佈所需的輸出嗎? – Terminus
@Terminus,期望的輸出只是'你好,@Angelina。我是@ Bob_Marley'(at)提到的字符串在輸出中是超鏈接的。 – Terungwa