Php 如何用html标记将所有单词括在字符串中?

Php 如何用html标记将所有单词括在字符串中?,php,regex,preg-replace,Php,Regex,Preg Replace,我需要将长度至少为2个字符的每个单词都包含在span标记之间的字符串中。所有问号、标点符号等都应保留在跨距之外(它们只能包含a-z以及特殊字符,如ñ、á、é等) 那么这个, Prenda de vestir que se ajusta? A la cintura y llega generalmente hasta el pie. 应该是这样的: <a href=http://example.com/prenda>Prenda</a> <a href=http:/

我需要将长度至少为2个字符的每个单词都包含在span标记之间的字符串中。所有问号、标点符号等都应保留在跨距之外(它们只能包含a-z以及特殊字符,如ñ、á、é等)

那么这个,

Prenda de vestir que se ajusta? A la cintura y llega generalmente hasta el pie.
应该是这样的:

<a href=http://example.com/prenda>Prenda</a> <a href=http://example.com/de>de</a> <a href=http://example.com/vestir>vestir</a> <a href=http://example.com/que>que</a> 
<a href=http://example.com/se>se</a> <a href=http://example.com/ajusta>ajusta</a>? A <a href=http://example.com/la>la</a> 
<a href=http://example.com/cintura>cintura</a> y <a href=http://example.com/llega>llega</a> 
<a href=http://example.com/generalmente>generalmente</a> <a href=http://example.com/hasta>hasta</a> <a href=http://example.com/el>el</a> <a href=http://example.com/pie>pie</a>.

? A.
Y
.
有什么想法吗?谢谢

改用这个:

\b(\w{2,})\b
基本上,
\b
表示“单词分隔符”(匹配单词的开头和结尾,不包括标点符号)
\w
是一个单词字符,但可以用
[a-zA-Z]
替换,以排除
[0-9]
字符。然后应用量词
{2,}
表示长度超过2个字符

替代者

<a href="http://example.com/$1">$1</a>

我一直很感激你。(转换为的示例。)

以下是一个示例:

<?
$without = "Prenda de vestir que se ajusta? A la cintura y llega generalmente hasta el pie.";
$with = preg_replace("/([A-Za-z]{2,})/", "<a href=\"http://example.com/\\1\">\\1</a>", $without);
print $with;
?>

使用以下方法:

$result = preg_replace('/\b[\p{L}\p{M}]{2,}\b/u', '<a href=http://example.com/$0>$0</a>', $subject);
编辑:

"
\b              # Assert position at a word boundary
[\p{L}\p{M}]    # Match a single character present in the list below
                # A character with the Unicode property “letter” (any kind of letter from any language)
                # A character with the Unicode property “mark” (a character intended to be combined with another character (e.g. accents, umlauts, enclosing boxes, etc.))
   {2,}         # Between 2 and unlimited times, as many times as possible, giving back as needed (greedy)
\b              # Assert position at a word boundary
"
$result = preg_replace_callback(
        '/\b[\p{L}\p{M}]{2,}\b/u',
        create_function(
            '$matches',
            'return <a href=http://example.com/strtolower($matches[0])>$matches[0]</a>;'
        ),
        $subject
);
$result=preg\u replace\u回调(
'/\b[\p{L}\p{M}]{2,}\b/u',,
创建函数(
“$matches”,
“返回;”
),
$subject
);

如果你先开始,也许会有帮助。呵呵,在我练习编写一段工作代码时,你的解决方案打败了我:)不错:)但是不能很好地处理特殊角色(ñ)效果很好!我可以用example/mb_strtolower($0)之类的东西替换example/$0吗?