2017-04-10 19 views
0

文字列内の最後のインスタンス(ドット)を削除する方法はありますか?PHPのピリオドの前に文字列を削除します

私はこれらの次の文字列があります。

  1. packageName.appName.moduleName.eventName.pageNameX
  2. packageName.appName.moduleName.pageNameY
  3. packageName.appName.pageNameZ
  4. packageName.pageNameA

そして、私は持っていたい:

  • pageNameA
  • 私が試してみました

  • pageNameZ
  • pageNameY
    1. pageNameX
    2. preg_replace('/^.*.\s*/', '', $theString); 
      

      が、それは動作しません。

    +2

    第2のドットはエスケープする必要があります。つまり、「\。」、そうでない場合は「任意の文字」となります。 – halfer

    +0

    'preg_replace( '/.*\./'、 ''、$ string); ' –

    答えて

    2

    substr($str, strrpos($str, '.')+1);

    strrpos()は、文字列内の文字の最後のインスタンスの位置を返します。その値+1を開始位置としてsubstr()に入力してください。

    +0

    ドットがない限り、これはうまくいくでしょう。 –

    +0

    彼のすべてのサンプルデータがあります。 –

    +0

    私は彼らがそうしなかったとは言わなかった。 –

    2

    あなたは

    $s = "packageName.appName.moduleName.eventName.pageNameX"; 
    preg_match('~[^.]+$~', $s, $match); 
    echo $match[0]; 
    

    でこれらの部分文字列にマッチするregex demoPHP demoを参照してください。

    詳細

    • [^.]+から.
    • $以外の1以上の文字 - 文字列の末尾。
    +0

    正しいです。しかし、代わりに 'preg_match'を使う方が良いと思います。 – wormi4ok

    +0

    はい、スタンドアロンの文字列の場合は、確かです。 –

    0

    この関数は、ピリオドを区切り記号として使用してパッケージパスをコンポーネントに分割します。次に、パッケージパスの分割時に配列内で取得されたコンポーネントの数を使用して、最後のコンポーネントの最後のコンポーネントを返します。

    function get_package_name($in_package_path){ 
    
        // Split package path into components at the periods. 
        $package_path_components = explode('.',$in_package_path); 
    
        // Get the total number of items in components array 
        // and subtract 1 to get array index as array indexes start at 0. 
        $last_package_path_component_index = count($package_path_components)-1; 
    
    // Return the last component of the package path. 
        return $package_path_components[$last_package_path_component_index] 
    } 
    
    関連する問題