如何使用 PHP 匹配字母数字和符号?

How to match alphanumeric and symbols using PHP?

我正在处理存储在变量 $title 中的 UTF8 编码文本内容。

使用 preg_replace,如果 $title 字符串以

结尾,我如何附加一个额外的 space

在行尾之前使用正后视。
并替换为 space。

$title = preg_replace('/(?<=[A-Za-z0-9?!])$/',' ', $title);

试一试here

您可能想尝试下面的模式匹配,看看是否适合您。

<?php
    // THE REGEX BELOW MATCHES THE ENDING LOWER & UPPER-CASED CHARACTERS, DIGITS
    // AND SYMBOLS LIKE "?" AND "!" AND EVEN A DOT "."
    // HOWEVER YOU CAN IMPROVISE ON YOUR OWN
    $rxPattern  = "#([\!\?a-zA-Z0-9\.])$#"; 
    $title      = "What is your name?";
    var_dump($title);

    // AND HERE, YOU APPEND A SINGLE SPACE AFTER THE MATCHED STRING
    $title      = preg_replace($rxPattern, " ", $title);
    var_dump($title);

   // THE FIRST var_dump($title) PRODUCES:
   // 'What is your name?' (length=18)

   // AND THE SECOND var_dump($title) PRODUCES
   // 'What is your name? ' (length=19) <== NOTICE THE LENGTH FROM ADDED SPACE.

你可以测试一下HERE

干杯...

你需要

$title=preg_replace("/.*[\w?!]$/", "\0 ", $title);

这应该可以解决问题:

preg_replace('/^(.*[\w?!])$/', " ", $string);

本质上它所做的是 如果 字符串以您不需要的字符之一结尾,它会附加一个 space.

如果字符串与模式不匹配,那么 preg_replace() returns 原始字符串 - 所以你仍然很好。

如果您需要扩展不需要的结局列表,您可以将它们添加到角色块中 [\w?!]