分裂字符串并保持句号

时间:2015-10-29 02:53:49

标签: php regex preg-replace preg-split

我正试图在。!保留它们,但由于某种原因,它不能正常工作。我做错了什么?

$input = "hi i am1. hi i am2.";
$inputX = preg_split("~[.!?]+\K\b~", $input); 

print_r($inputX);

结果:

Array ( [0] => hi i am1. hi i am2. )

预期结果:

Array ( [0] => hi i am1. [1] => hi i am2. )

3 个答案:

答案 0 :(得分:2)

我不确定您是否需要执行package com.client.businesstracker.activity; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.android.volley.Request.Method; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; import com.client.businesstracker.Login; import com.client.businesstracker.R; import com.client.businesstracker.loginandregistration.app.AppConfig; import com.client.businesstracker.loginandregistration.app.AppController; import com.client.businesstracker.loginandregistration.helper.SQLiteHandler; import com.client.businesstracker.loginandregistration.helper.SessionManager; public class LoginActivity extends Activity { private static final String TAG = RegisterActivity.class.getSimpleName(); private Button btnLogin; private Button btnLinkToRegister; private EditText inputServerID; private EditText inputClientID; private EditText inputPassword; private ProgressDialog pDialog; private SessionManager session; private SQLiteHandler db; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); inputServerID = (EditText) findViewById(R.id.serverID); inputClientID = (EditText) findViewById(R.id.clientID); inputPassword = (EditText) findViewById(R.id.password); btnLogin = (Button) findViewById(R.id.btnLogin); btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen); // Progress dialog pDialog = new ProgressDialog(this); pDialog.setCancelable(false); // SQLite database handler db = new SQLiteHandler(getApplicationContext()); // Session manager session = new SessionManager(getApplicationContext()); // Check if user is already logged in or not if (session.isLoggedIn()) { // User is already logged in. Take him to main activity Intent intent = new Intent(LoginActivity.this, Login.class); startActivity(intent); finish(); } // Login button Click Event btnLogin.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { String serverID = inputServerID.getText().toString().trim(); String clientID = inputClientID.getText().toString().trim(); String password = inputPassword.getText().toString().trim(); // Check for empty data in the form if (!serverID.isEmpty() && !password.isEmpty() && !clientID.isEmpty()) { // login user checkLogin(serverID, clientID,password); } else { // Prompt user to enter credentials Toast.makeText(getApplicationContext(), "Please enter the credentials!", Toast.LENGTH_LONG) .show(); } } }); // Link to Register Screen btnLinkToRegister.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent i = new Intent(getApplicationContext(), RegisterActivity.class); startActivity(i); finish(); } }); } /** * function to verify login details in mysql db * */ private void checkLogin(final String serverID, final String clientID, final String password) { // Tag used to cancel the request String tag_string_req = "req_login"; pDialog.setMessage("Logging in ..."); showDialog(); StringRequest strReq = new StringRequest(Method.POST, AppConfig.URL_LOGIN, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d(TAG, "Login Response: " + response.toString()); hideDialog(); try { JSONObject jObj = new JSONObject(response); boolean error = jObj.getBoolean("error"); // Check for error node in json if (!error) { // user successfully logged in // Create login session session.setLogin(true); // Now store the user in SQLite String uid = jObj.getString("uid"); JSONObject user = jObj.getJSONObject("user"); String name = user.getString("name"); String serverID = user.getString("serverID"); String clientID = user.getString("clientID"); // Inserting row in users table db.addUser(name, serverID, clientID); // Launch main activity Intent intent = new Intent(LoginActivity.this, Login.class); startActivity(intent); finish(); } else { // Error in login. Get the error message String errorMsg = jObj.getString("error_msg"); Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_LONG).show(); } } catch (JSONException e) { // JSON error e.printStackTrace(); Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e(TAG, "Login Error: " + error.getMessage()); Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show(); hideDialog(); } }) { @Override protected Map<String, String> getParams() { // Posting parameters to login url Map<String, String> params = new HashMap<String, String>(); params.put("serverID", serverID); params.put("clientID", clientID); params.put("password", password); return params; } }; // Adding request to request queue AppController.getInstance().addToRequestQueue(strReq, tag_string_req); } private void showDialog() { if (!pDialog.isShowing()) pDialog.show(); } private void hideDialog() { if (pDialog.isShowing()) pDialog.dismiss(); } 但是如果可以选择preg_split()则尝试preg_match_all()

$input = "hi i am1. hi i am2.";
preg_match_all("/[^\.\?\!]+[\.\!\?]/", $input,$matched);
print_r($matched);

给你:

Array
(
    [0] => Array
        (
            [0] => hi i am1.
            [1] =>  hi i am2.
        )
)

答案 1 :(得分:1)

尝试不使用\b,我认为这是多余的(如果不是这种情况)。

$input = "hi i am1. hi i am2.?! hi i am2.?";
$inputX = preg_split("~(?>[.!?]+)\K(?!$)~", $input); 

print_r($inputX);

(?!$)是为了避免在匹配的元素上拆分,如果它在字符串的末尾,那么就不会有额外的空结果。原子分组?>是为了避免分裂,如果字符串末尾有一系列字符,如?!.(没有原子分组,它会在!上分割,最后的结果是单个char .)。输出:

Array
(
    [0] => hi i am1.
    [1] =>  hi i am2.?!
    [2] =>  hi i am2.?
)

答案 2 :(得分:0)

我希望这是你所期待的

$input = "hi i am1. hi i !am?2."; // i have added other ?! symbols also

$inputX = preg_split("/(\.|\!|\?)/", $input,-1,PREG_SPLIT_DELIM_CAPTURE); 

print_r($inputX)

输出:

Array ( [0] => hi i am1 [1] => . [2] => hi i [3] => ! [4] => am [5] => ? [6] => 2 [7] => . [8] => )