Home  >  Article  >  Backend Development  >  How to extract part of a string

How to extract part of a string

王林
王林forward
2024-02-08 22:39:221129browse

How to extract part of a string

php editor Apple brings you an article on how to extract part of a string. In programming, we often need to extract the required part from a string, such as getting the file extension, intercepting a piece of text, etc. This article will introduce several commonly used methods and functions to help you easily implement the string extraction function. Whether you are a beginner or a developer with some programming experience, this article can provide you with practical tips and methods to get twice the result with half the effort when processing strings. Come and learn!

Question content

I need to get part of the string, namely: { "Token":"eyJ0eXjskdckjasdcaksdclkasdcsjnsc", "Timestamp expired": 9234234 }

I have tried using split, splitafter. I need to get this token, just the token.

Workaround

You should parse it as map[string]interface{}:

jsoninput := []byte(`{ "token":"eyj0exjskdckjasdcaksdclkasdcsjnsc", "expiresontimestamp":9234234 }`)
jsoncontent := make(map[string]interface{})

unmarshalerr := json.unmarshal(jsoninput, &jsoncontent)

if unmarshalerr != nil {
    panic(unmarshalerr)
}

token, _ := jsoncontent["token"].(string)

Or create a dedicated struct for unmarshalling:

type Token struct {
    Value              string `json:"token"`
    ExpiresOnTimestamp int    `json:"expiresOnTimestamp"`
}

jsonInput := []byte(`{ "token":"eyJ0eXjskdckjasdcaksdclkasdcsjnsc", "expiresOnTimestamp":9234234 }`)

var jsonContent Token

unmarshalErr := json.Unmarshal(jsonInput, &jsonContent)

if unmarshalErr != nil {
    panic(unmarshalErr)
}

token := jsonContent.Value

The above is the detailed content of How to extract part of a string. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete