我正在尝试在字符串中替换这些标签[mtgcard] cardname [/ mtgcard],但是在替换时,我还希望cardname成为一部分超链接(下面的示例)这是我用来从字符串中获取CARDNAMES的函数(在stackoverflow上找到):
function getContents($str, $startDelimiter, $endDelimiter) { $contents = array(); $startDelimiterLength = strlen($startDelimiter); $endDelimiterLength = strlen($endDelimiter); $startFrom = $contentStart = $contentEnd = 0; while (false !== ($contentStart = strpos($str, $startDelimiter, $startFrom))) { $contentStart += $startDelimiterLength; $contentEnd = strpos($str, $endDelimiter, $contentStart); if (false === $contentEnd) { break; } $contents[] = substr($str, $contentStart, $contentEnd - $contentStart); $startFrom = $contentEnd + $endDelimiterLength; } return $contents; }
而且效果很好,下面是我将替换标签的字符串:
$string = "we have a card [mtgcard]tarmogoyf[/mtgcard] "; $string .= "and [mtgcard]forest[/mtgcard] "; //here i get all the values between [mtgcard] [/mtgcard] $arr = getContents($string, '[mtgcard]', '[/mtgcard]');
这给了我
Array ( [0] => tarmogoyf [1] => forest )
//I count them for te loop $count = count($arr); for($i = 0; $i < $count; $i++) { //here I replace the [mtgcard] with <a href='https://deckbox.org/mtg/*HERE SHOULD BE THE value between tags*'> //and [/mtgcard] with </a> $string = str_ireplace(array("[mtgcard]", "[/mtgcard]"),array("<a href='https://deckbox.org/mtg/'>", "</a>"), $string); $arr[$i]++; } echo $string;
上面的脚本显示:
we have a card 1. <a href="https://deckbox.org/mtg/">tarmogoyf</a> 2. <a href="https://deckbox.org/mtg/">forest</a>
这完全是我想要的,但部分是因为我想完成带有卡名的超链接,以为例如https://deckbox.org/mtg/cardname提供正确的路径>
为此,尝试了以上更改的上述FOR循环:
$count = count($arr); for($i = 0; $i < count($arr); $i++) { $string = str_ireplace(array("[mtgcard]", "[/mtgcard]"),array("<a href='https://deckbox.org/mtg/$arr[$i]'>", "</a>"), $string); $arr[$i]++; }
我得到这个结果:
1. <a href="https://deckbox.org/mtg/tarmogoyf">tarmogoyf</a> 2. <a href="https://deckbox.org/mtg/tarmogoyf">forest</a>
所有超链接的第一个值为array($ arr),我也尝试了嵌套的foreach循环,但输出重复两次。我想要的是:
1. <a href="https://deckbox.org/mtg/tarmogoyf">tarmogoyf</a> 2. <a href="https://deckbox.org/mtg/forest">forest</a>
关于改善脚本质量的任何建议也将被接受。
我正在尝试在字符串中替换这些标签[mtgcard]卡名[/ mtgcard],但是在替换时,我还希望卡名成为超链接的一部分(下面的示例)这是函数(位于.. 。
使用preg_replace
进行基于正则表达式的替换最容易实现:
$string = "we have a card [mtgcard]tarmogoyf[/mtgcard] ";
$string .= "and [mtgcard]forest[/mtgcard] ";
$string = preg_replace('/\[mtgcard\](.*?)\[\/mtgcard\]/', '<a href="https://deckbox.org/mtg/$1">$1</a>', $string);
echo $string;