在php中添加/修复标点符号


Add/fix punctuation in php

我正在慢慢完善PHP中的一个标点符号修复函数,该函数用于清理用户输入。该函数目前在标点符号后添加空格,删除标点符号前的空格,并将每个句子的第一个单词大写。我看到一些人在寻找类似的功能,所以我很高兴与大家分享我迄今为止所拥有的。它非常接近我想要的位置,然而,当它在逗号后面添加空格时,当逗号位于1000等数字内时,应该避免这样做。有人能建议修改我的代码以忽略数字内逗号的最快方法吗?也许有一些方法可以缩短我所拥有的,但仍然能达到同样的结果?谢谢你抽出时间。。。

function format_punc($string){
    $punctuation = ',.;:';
    $string = str_replace(' ?', '?', str_replace(' .', '.', str_replace(' ,', ',', preg_replace('/(['.$punctuation.'])['s]*/', ''1 ', $string))));
    $string = trim(preg_replace('/[[:space:]]+/', ' ', preg_replace('/(['.!'?]'s+|'A)('w)/e', '"$1" . strtoupper("$2")', $string)));
    if($string[strlen($string)-1]==','){
        $string = substr($string, 0, -1).'.';
    }
    return $string;
}

这是我更新的php修复标点符号函数。。。它现在似乎工作正常。我确信有一些方法可以浓缩它,但它可以对字符串执行以下操作。。。

减少重复的标点符号,如!!到
将多个空间减少为单个空间
删除?之前的所有空格,
在;之后添加空格:
在逗号后添加空格,但当逗号是数字的一部分时不添加空格
在句点后添加空格,但当句点是数字或缩写的一部分时不添加空格
删除字符串开头和结尾的空白
将句子的第一个单词大写
如果最后一个字符是逗号,请将其更改为句点

function format_punc($string){
    $punctuation = ';:';
    $spaced_punc = array(' ?', ' .', ' ,');
    $un_spaced_punc = array('?', '.', ',');
    $string = preg_replace("/([.,!?;:])+/iS","$1",$string);
    $string = preg_replace('/[[:space:]]+/', ' ', $string);
    $string = str_replace($spaced_punc, $un_spaced_punc, $string);
    $string = preg_replace('/(['.$punctuation.'])['s]*/', ''1 ', $string);
    $string = preg_replace('/(?<!'d),|,(?!'d{3})/', ', ', $string);
    $string = preg_replace('/('.)([[:alpha:]]{2,})/', '$1 $2', $string);
    $string = trim($string);
    $string = preg_replace('/(['.!'?]'s+|'A)('w)/e', '"$1" . strtoupper("$2")', $string);
    if($string[strlen($string)-1]==','){
        $string = substr($string, 0, -1).'.';
    }
    return $string;
}

如果你花时间压缩这个代码,并创建仍然返回相同结果的东西,请分享!谢谢你,享受吧!

我认为正则表达式应该是([^0-9][.][^0-9])[''s]*

preg_replace('/([^0-9]['.$punctuation.'][^0-9])['s]*/', ''1 ', $string)

链接到regexp测试

这有点复杂,但它应该会让你朝着正确的方向前进:

<?php
// The following finds all commas in $string and identifies which comma is preceded and followed by a number
$string = 'Hello, my name, is John,Doe. I have 3,425 cats.';
function strpos_r($haystack, $needle)
{
    if(strlen($needle) > strlen($haystack))
        trigger_error(sprintf("%s: length of argument 2 must be <= argument 1", __FUNCTION__), E_USER_WARNING);
    $seeks = array();
    while($seek = strrpos($haystack, $needle))
    {
        array_push($seeks, $seek);
        $haystack = substr($haystack, 0, $seek);
    }
    return $seeks;
}
var_dump($commas = strpos_r($string, ',')); // gives you the location of all commas
for ($i = 0; i <= count($commas) - 1; $i++)
{
    if (is_numeric($commas[$i] - 1) && is_numeric($commas[$i] + 1)) 
    {
      // this means the characters before and after a given comma are numeric
      // don't add space (or delete the space) here
    }
}